react-native-nitro-sse 3.2.0-beta.1 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -27
- package/android/build.gradle +7 -3
- package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +8 -32
- package/android/src/main/java/com/margelo/nitro/nitrosse/NetworkInspector.kt +124 -6
- package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +439 -509
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +137 -316
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +18 -8
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventReader.kt +231 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseFailureClassifier.kt +245 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseMetrics.kt +237 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +13 -6
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +48 -22
- package/ios/NitroSse.swift +402 -484
- package/ios/SseConfig+CopyWith.swift +0 -2
- package/ios/SseConnectionHandler.swift +238 -446
- package/ios/SseDispatchQueueDispatcher.swift +7 -7
- package/ios/SseDispatcher.swift +5 -4
- package/ios/SseEventBuffer.swift +24 -23
- package/ios/SseEventParser.swift +360 -0
- package/ios/SseFailureClassifier.swift +249 -0
- package/ios/SseLifecycleManager.swift +19 -14
- package/ios/SseMetrics.swift +188 -0
- package/ios/SseNetworkMonitor.swift +18 -14
- package/ios/SseReconnectStrategy.swift +28 -30
- package/lib/module/FetchSseDriver.js +398 -170
- package/lib/module/MockSseEngine.js +15 -17
- package/lib/module/NitroSseClient.js +70 -56
- package/lib/module/SseConsoleLogger.js +64 -0
- package/lib/module/SseEventParser.js +173 -115
- package/lib/module/createNitroSse.js +7 -14
- package/lib/module/createNitroSse.native.js +2 -1
- package/lib/module/useNitroSse.js +103 -90
- package/lib/typescript/src/FetchSseDriver.d.ts +11 -4
- package/lib/typescript/src/MockSseEngine.d.ts +2 -2
- package/lib/typescript/src/NitroSse.nitro.d.ts +9 -1
- package/lib/typescript/src/NitroSseClient.d.ts +4 -1
- package/lib/typescript/src/SseConsoleLogger.d.ts +28 -0
- package/lib/typescript/src/SseEventParser.d.ts +18 -2
- package/lib/typescript/src/SseInterface.d.ts +21 -4
- package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.hpp +1 -1
- package/nitrogen/generated/android/c++/JFunc_void_std__vector_SseEvent_.hpp +1 -1
- package/nitrogen/generated/android/c++/JHttpMethod.hpp +1 -1
- package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +1 -1
- package/nitrogen/generated/android/c++/JHybridNitroSseSpec.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseConfig.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseDisconnectReason.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseEvent.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseEventType.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseMockConfig.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseMockEvent.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseMockMode.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseState.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseStats.hpp +1 -1
- 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 +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/Func_void_std__vector_SseEvent_.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HttpMethod.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HybridNitroSseSpec.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseDisconnectReason.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEvent.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEventType.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockConfig.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockEvent.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockMode.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseState.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseStats.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/nitrosseOnLoad.kt +1 -1
- package/nitrogen/generated/android/nitrosse+autolinking.cmake +1 -1
- package/nitrogen/generated/android/nitrosse+autolinking.gradle +1 -1
- package/nitrogen/generated/android/nitrosseOnLoad.cpp +1 -1
- package/nitrogen/generated/android/nitrosseOnLoad.hpp +1 -1
- package/nitrogen/generated/ios/NitroSse+autolinking.rb +1 -1
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.cpp +1 -1
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +1 -1
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +1 -1
- package/nitrogen/generated/ios/NitroSseAutolinking.mm +1 -1
- package/nitrogen/generated/ios/NitroSseAutolinking.swift +1 -5
- package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.cpp +1 -1
- package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +1 -1
- package/nitrogen/generated/ios/swift/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.swift +1 -1
- package/nitrogen/generated/ios/swift/Func_void_std__exception_ptr.swift +1 -1
- package/nitrogen/generated/ios/swift/Func_void_std__shared_ptr_Promise_std__unordered_map_std__string__std__string___.swift +1 -1
- package/nitrogen/generated/ios/swift/Func_void_std__unordered_map_std__string__std__string_.swift +1 -1
- package/nitrogen/generated/ios/swift/Func_void_std__vector_SseEvent_.swift +1 -1
- package/nitrogen/generated/ios/swift/HttpMethod.swift +1 -1
- package/nitrogen/generated/ios/swift/HybridNitroSseSpec.swift +1 -1
- package/nitrogen/generated/ios/swift/HybridNitroSseSpec_cxx.swift +3 -3
- package/nitrogen/generated/ios/swift/SseConfig.swift +1 -1
- package/nitrogen/generated/ios/swift/SseDisconnectReason.swift +1 -1
- package/nitrogen/generated/ios/swift/SseEvent.swift +1 -1
- package/nitrogen/generated/ios/swift/SseEventType.swift +1 -1
- package/nitrogen/generated/ios/swift/SseMockConfig.swift +1 -1
- package/nitrogen/generated/ios/swift/SseMockEvent.swift +1 -1
- package/nitrogen/generated/ios/swift/SseMockMode.swift +1 -1
- package/nitrogen/generated/ios/swift/SseState.swift +1 -1
- package/nitrogen/generated/ios/swift/SseStats.swift +1 -1
- package/nitrogen/generated/shared/c++/HttpMethod.hpp +1 -1
- package/nitrogen/generated/shared/c++/HybridNitroSseSpec.cpp +1 -1
- package/nitrogen/generated/shared/c++/HybridNitroSseSpec.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseConfig.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseDisconnectReason.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseEvent.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseEventType.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseMockConfig.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseMockEvent.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseMockMode.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseState.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseStats.hpp +1 -1
- package/package.json +18 -10
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
internal enum SseFailureDisconnectCategory: Equatable {
|
|
4
|
+
case parserError
|
|
5
|
+
case serverError
|
|
6
|
+
case timeout
|
|
7
|
+
case networkError
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
internal struct SseFailureContext {
|
|
11
|
+
let response: HTTPURLResponse?
|
|
12
|
+
let errorBody: String?
|
|
13
|
+
let nsError: NSError
|
|
14
|
+
let httpStatusCode: Int?
|
|
15
|
+
let reportedStatusCode: Int
|
|
16
|
+
let isTimeout: Bool
|
|
17
|
+
let isParserLimit: Bool
|
|
18
|
+
let isInvalidContentType: Bool
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
internal struct SseFailurePolicyInput {
|
|
22
|
+
let hasInterceptor: Bool
|
|
23
|
+
let nextAuthAttempt: Int
|
|
24
|
+
let maxAuthRetries: Int
|
|
25
|
+
let maxRetryIntervalSeconds: TimeInterval
|
|
26
|
+
let retryAfterJitterSeconds: TimeInterval
|
|
27
|
+
|
|
28
|
+
init(
|
|
29
|
+
hasInterceptor: Bool,
|
|
30
|
+
nextAuthAttempt: Int,
|
|
31
|
+
maxAuthRetries: Int,
|
|
32
|
+
maxRetryIntervalSeconds: TimeInterval,
|
|
33
|
+
retryAfterJitterSeconds: TimeInterval = Double.random(in: 0.5...1.5)
|
|
34
|
+
) {
|
|
35
|
+
self.hasInterceptor = hasInterceptor
|
|
36
|
+
self.nextAuthAttempt = nextAuthAttempt
|
|
37
|
+
self.maxAuthRetries = maxAuthRetries
|
|
38
|
+
self.maxRetryIntervalSeconds = maxRetryIntervalSeconds
|
|
39
|
+
self.retryAfterJitterSeconds = retryAfterJitterSeconds
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
internal enum SseFailureDecision: Equatable {
|
|
44
|
+
case failAndStop(message: String, statusCode: Double?)
|
|
45
|
+
case authLimitReached(message: String, statusCode: Double)
|
|
46
|
+
case authRetry(message: String, statusCode: Double)
|
|
47
|
+
case retryAfter(message: String, statusCode: Double, delaySeconds: TimeInterval)
|
|
48
|
+
case rateLimitBackoff(message: String, statusCode: Double)
|
|
49
|
+
case transientRetry(message: String, statusCode: Double, markStale: Bool)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/// Pure classifier translating transport, parser, and HTTP errors into disconnection metrics and retry decisions.
|
|
53
|
+
internal enum SseFailureClassifier {
|
|
54
|
+
static func isEventStreamMimeType(_ contentType: String) -> Bool {
|
|
55
|
+
let rawMime = contentType.split(separator: ";", omittingEmptySubsequences: false).first
|
|
56
|
+
let mimeType = rawMime?.trimmingCharacters(in: .whitespaces).lowercased() ?? ""
|
|
57
|
+
return mimeType == "text/event-stream"
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
static func resolveHttpStatusCode(response: HTTPURLResponse?, nsError: NSError) -> Int? {
|
|
61
|
+
// Decouple HTTP status code (meaningful only for HTTP 4xx/5xx or non-200 2xx) from transport/parser codes
|
|
62
|
+
if let resp = response, resp.statusCode >= 400 || ((200..<300).contains(resp.statusCode) && resp.statusCode != 200) {
|
|
63
|
+
return resp.statusCode
|
|
64
|
+
}
|
|
65
|
+
if nsError.code >= 100 && nsError.code < 600 {
|
|
66
|
+
return nsError.code
|
|
67
|
+
}
|
|
68
|
+
return nil
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
static func isInvalidEventStreamContentType(response: HTTPURLResponse?, nsError: NSError) -> Bool {
|
|
72
|
+
if nsError.domain == "NitroSse" && nsError.code == -2001 {
|
|
73
|
+
return true
|
|
74
|
+
}
|
|
75
|
+
guard let resp = response, (200..<300).contains(resp.statusCode) else {
|
|
76
|
+
return false
|
|
77
|
+
}
|
|
78
|
+
let rawContentType = resp.value(forHTTPHeaderField: "Content-Type") ??
|
|
79
|
+
(resp.allHeaderFields["Content-Type"] as? String) ?? ""
|
|
80
|
+
return !isEventStreamMimeType(rawContentType)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
static func buildContext(
|
|
84
|
+
error: Error,
|
|
85
|
+
response: HTTPURLResponse?,
|
|
86
|
+
errorBody: String?
|
|
87
|
+
) -> SseFailureContext {
|
|
88
|
+
let nsError = error as NSError
|
|
89
|
+
let httpStatusCode = resolveHttpStatusCode(response: response, nsError: nsError)
|
|
90
|
+
return SseFailureContext(
|
|
91
|
+
response: response,
|
|
92
|
+
errorBody: errorBody,
|
|
93
|
+
nsError: nsError,
|
|
94
|
+
httpStatusCode: httpStatusCode,
|
|
95
|
+
reportedStatusCode: httpStatusCode ?? nsError.code,
|
|
96
|
+
isTimeout: nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorTimedOut,
|
|
97
|
+
isParserLimit: nsError.domain == "NitroSse" && (nsError.code == -2002 || nsError.code == -2003),
|
|
98
|
+
isInvalidContentType: isInvalidEventStreamContentType(response: response, nsError: nsError)
|
|
99
|
+
)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
static func disconnectCategory(
|
|
103
|
+
for context: SseFailureContext,
|
|
104
|
+
hasAttemptParseError: Bool
|
|
105
|
+
) -> SseFailureDisconnectCategory {
|
|
106
|
+
if context.isParserLimit || hasAttemptParseError {
|
|
107
|
+
return .parserError
|
|
108
|
+
}
|
|
109
|
+
if context.isInvalidContentType ||
|
|
110
|
+
context.httpStatusCode == 204 ||
|
|
111
|
+
(context.httpStatusCode ?? 0) >= 400 {
|
|
112
|
+
return .serverError
|
|
113
|
+
}
|
|
114
|
+
if context.isTimeout {
|
|
115
|
+
return .timeout
|
|
116
|
+
}
|
|
117
|
+
return .networkError
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
static func errorCodeString(for context: SseFailureContext) -> String {
|
|
121
|
+
let codeValue = context.httpStatusCode ?? context.nsError.code
|
|
122
|
+
return "\(context.nsError.domain)(\(codeValue))"
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
static func classify(context: SseFailureContext, policy: SseFailurePolicyInput) -> SseFailureDecision {
|
|
126
|
+
if let terminal = classifyTerminal(context) {
|
|
127
|
+
return terminal
|
|
128
|
+
}
|
|
129
|
+
if let auth = classifyAuth(httpStatusCode: context.httpStatusCode, policy: policy) {
|
|
130
|
+
return auth
|
|
131
|
+
}
|
|
132
|
+
if let rateLimit = classifyRetryAfterOrRateLimit(context: context, policy: policy) {
|
|
133
|
+
return rateLimit
|
|
134
|
+
}
|
|
135
|
+
return .transientRetry(
|
|
136
|
+
message: buildDefaultErrorMessage(context),
|
|
137
|
+
statusCode: Double(context.reportedStatusCode),
|
|
138
|
+
markStale: context.isTimeout
|
|
139
|
+
)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
private static func classifyTerminal(_ context: SseFailureContext) -> SseFailureDecision? {
|
|
143
|
+
// WHATWG EventSource Section 7: HTTP 204 No Content explicitly terminates stream across platforms.
|
|
144
|
+
if context.httpStatusCode == 204 {
|
|
145
|
+
return .failAndStop(message: "No Content (204). Stopping.", statusCode: 204)
|
|
146
|
+
}
|
|
147
|
+
if context.isInvalidContentType {
|
|
148
|
+
return .failAndStop(
|
|
149
|
+
message: "Invalid Content-Type: expected text/event-stream. Stopping.",
|
|
150
|
+
statusCode: Double(context.reportedStatusCode)
|
|
151
|
+
)
|
|
152
|
+
}
|
|
153
|
+
if let nonOkSuccess = context.httpStatusCode, (200..<300).contains(nonOkSuccess), nonOkSuccess != 200 {
|
|
154
|
+
return .failAndStop(
|
|
155
|
+
message: "HTTP \(nonOkSuccess) is not a valid SSE response. Stopping.",
|
|
156
|
+
statusCode: Double(nonOkSuccess)
|
|
157
|
+
)
|
|
158
|
+
}
|
|
159
|
+
if context.isParserLimit {
|
|
160
|
+
return .failAndStop(
|
|
161
|
+
message: context.nsError.localizedDescription,
|
|
162
|
+
statusCode: Double(context.reportedStatusCode)
|
|
163
|
+
)
|
|
164
|
+
}
|
|
165
|
+
if let fatalHttp = context.httpStatusCode,
|
|
166
|
+
(400...499).contains(fatalHttp),
|
|
167
|
+
![401, 403, 408, 429].contains(fatalHttp) {
|
|
168
|
+
let fatalMessage = formatErrorBodyPreview(context.errorBody)
|
|
169
|
+
.map { "Fatal Error (\(fatalHttp)): \($0)" }
|
|
170
|
+
?? "Fatal Error (\(fatalHttp)). Stopping."
|
|
171
|
+
return .failAndStop(message: fatalMessage, statusCode: Double(fatalHttp))
|
|
172
|
+
}
|
|
173
|
+
return nil
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
private static func classifyAuth(
|
|
177
|
+
httpStatusCode: Int?,
|
|
178
|
+
policy: SseFailurePolicyInput
|
|
179
|
+
) -> SseFailureDecision? {
|
|
180
|
+
// HTTP 401/403 Auth errors trigger token refresh via onBeforeRequest interceptor up to maxAuthRetries.
|
|
181
|
+
guard let http = httpStatusCode, http == 401 || http == 403 else {
|
|
182
|
+
return nil
|
|
183
|
+
}
|
|
184
|
+
if !policy.hasInterceptor {
|
|
185
|
+
return .failAndStop(
|
|
186
|
+
message: "Auth Error (\(http)) - No interceptor provided. Stopping.",
|
|
187
|
+
statusCode: Double(http)
|
|
188
|
+
)
|
|
189
|
+
}
|
|
190
|
+
if policy.nextAuthAttempt > policy.maxAuthRetries {
|
|
191
|
+
return .authLimitReached(
|
|
192
|
+
message: "Auth Error (\(http)) - Retry limit reached (\(policy.maxAuthRetries)). Stopping.",
|
|
193
|
+
statusCode: Double(http)
|
|
194
|
+
)
|
|
195
|
+
}
|
|
196
|
+
return .authRetry(
|
|
197
|
+
message: "Auth Error (\(http)) - Retry \(policy.nextAuthAttempt)/\(policy.maxAuthRetries). " +
|
|
198
|
+
"Refreshing token...",
|
|
199
|
+
statusCode: Double(http)
|
|
200
|
+
)
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
private static func classifyRetryAfterOrRateLimit(
|
|
204
|
+
context: SseFailureContext,
|
|
205
|
+
policy: SseFailurePolicyInput
|
|
206
|
+
) -> SseFailureDecision? {
|
|
207
|
+
// HTTP 429/503: Honor server Retry-After delay with randomized jitter to prevent thundering herd.
|
|
208
|
+
let retryAfterSeconds = context.response.flatMap { SseReconnectStrategy.extractRetryAfterSeconds(from: $0) }
|
|
209
|
+
if let http = context.httpStatusCode, http == 429 || http == 503, let retryAfter = retryAfterSeconds {
|
|
210
|
+
let boundedRetryAfter = max(0.0, min(retryAfter, policy.maxRetryIntervalSeconds))
|
|
211
|
+
let totalDelay = max(1.0, boundedRetryAfter + policy.retryAfterJitterSeconds)
|
|
212
|
+
return .retryAfter(
|
|
213
|
+
message: "Retry-After received: \(Int(totalDelay))s",
|
|
214
|
+
statusCode: Double(http),
|
|
215
|
+
delaySeconds: totalDelay
|
|
216
|
+
)
|
|
217
|
+
}
|
|
218
|
+
// HTTP 429 without Retry-After: Fallback to exponential backoff as rate limits are recoverable.
|
|
219
|
+
if context.httpStatusCode == 429 {
|
|
220
|
+
return .rateLimitBackoff(
|
|
221
|
+
message: "Rate Limited (429). Retrying with backoff...",
|
|
222
|
+
statusCode: 429
|
|
223
|
+
)
|
|
224
|
+
}
|
|
225
|
+
return nil
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
private static let maxErrorMessageBodyChars = 256
|
|
229
|
+
|
|
230
|
+
private static func formatErrorBodyPreview(_ errorBody: String?) -> String? {
|
|
231
|
+
guard let trimmed = errorBody?.trimmingCharacters(in: .whitespacesAndNewlines),
|
|
232
|
+
!trimmed.isEmpty else {
|
|
233
|
+
return nil
|
|
234
|
+
}
|
|
235
|
+
if trimmed.count > maxErrorMessageBodyChars {
|
|
236
|
+
return String(trimmed.prefix(maxErrorMessageBodyChars)) + "…"
|
|
237
|
+
}
|
|
238
|
+
return trimmed
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
private static func buildDefaultErrorMessage(_ context: SseFailureContext) -> String {
|
|
242
|
+
if let http = context.httpStatusCode,
|
|
243
|
+
http >= 500,
|
|
244
|
+
let bodyPreview = formatErrorBodyPreview(context.errorBody) {
|
|
245
|
+
return "Server Error (\(http)): \(bodyPreview)"
|
|
246
|
+
}
|
|
247
|
+
return context.nsError.localizedDescription
|
|
248
|
+
}
|
|
249
|
+
}
|
|
@@ -3,20 +3,22 @@ import Foundation
|
|
|
3
3
|
import UIKit
|
|
4
4
|
#endif
|
|
5
5
|
|
|
6
|
-
/// Monitors iOS app lifecycle notifications (`didEnterBackground`, `willEnterForeground`)
|
|
6
|
+
/// Monitors iOS app lifecycle notifications (`didEnterBackground`, `willEnterForeground`)
|
|
7
|
+
/// and manages `UIBackgroundTask`.
|
|
7
8
|
/// Decouples iOS platform lifecycle hooks from connection state transitions.
|
|
8
9
|
class SseLifecycleManager {
|
|
9
10
|
private let dispatcher: SseDispatcher
|
|
10
11
|
private let onBackground: () -> Void
|
|
11
12
|
private let onForeground: () -> Void
|
|
12
|
-
|
|
13
|
+
|
|
13
14
|
private(set) var isAppInBackground: Bool = false
|
|
14
|
-
|
|
15
|
+
private var isObserving: Bool = false
|
|
16
|
+
|
|
15
17
|
#if os(iOS)
|
|
16
18
|
private var backgroundTaskIdentifier: UIBackgroundTaskIdentifier = .invalid
|
|
17
19
|
private var isBackgroundTaskActive: Bool = false
|
|
18
20
|
#endif
|
|
19
|
-
|
|
21
|
+
|
|
20
22
|
init(
|
|
21
23
|
dispatcher: SseDispatcher,
|
|
22
24
|
onBackground: @escaping () -> Void,
|
|
@@ -26,18 +28,18 @@ class SseLifecycleManager {
|
|
|
26
28
|
self.onBackground = onBackground
|
|
27
29
|
self.onForeground = onForeground
|
|
28
30
|
}
|
|
29
|
-
|
|
31
|
+
|
|
30
32
|
/// Ensures notification observers are unregistered and active background tasks are ended on deallocation.
|
|
31
33
|
deinit {
|
|
32
34
|
stopObserving()
|
|
33
35
|
cleanupBackgroundTask()
|
|
34
36
|
}
|
|
35
|
-
|
|
37
|
+
|
|
36
38
|
/// Registers observer for iOS application state transitions via `NotificationCenter`.
|
|
37
|
-
/// Calls `removeObserver(self)` first to guarantee idempotency without mutable state.
|
|
38
39
|
func startObserving() {
|
|
39
40
|
#if os(iOS)
|
|
40
|
-
|
|
41
|
+
guard !isObserving else { return }
|
|
42
|
+
isObserving = true
|
|
41
43
|
NotificationCenter.default.addObserver(
|
|
42
44
|
self,
|
|
43
45
|
selector: #selector(handleAppDidEnterBackground),
|
|
@@ -52,14 +54,17 @@ class SseLifecycleManager {
|
|
|
52
54
|
)
|
|
53
55
|
#endif
|
|
54
56
|
}
|
|
55
|
-
|
|
57
|
+
|
|
56
58
|
/// Unregisters all lifecycle notification observers.
|
|
57
59
|
func stopObserving() {
|
|
58
60
|
#if os(iOS)
|
|
61
|
+
guard isObserving else { return }
|
|
62
|
+
isObserving = false
|
|
63
|
+
// swiftlint:disable:next notification_center_detachment
|
|
59
64
|
NotificationCenter.default.removeObserver(self)
|
|
60
65
|
#endif
|
|
61
66
|
}
|
|
62
|
-
|
|
67
|
+
|
|
63
68
|
/// Begins a `UIBackgroundTask` to request background execution time from iOS.
|
|
64
69
|
/// `UIApplication` background task calls are routed through `DispatchQueue.main` as required by UIKit,
|
|
65
70
|
/// while task expiration callbacks dispatch safely back to the serial `SseDispatcher`.
|
|
@@ -67,7 +72,7 @@ class SseLifecycleManager {
|
|
|
67
72
|
#if os(iOS)
|
|
68
73
|
cleanupBackgroundTask()
|
|
69
74
|
isBackgroundTaskActive = true
|
|
70
|
-
|
|
75
|
+
|
|
71
76
|
DispatchQueue.main.async { [weak self] in
|
|
72
77
|
let taskId = UIApplication.shared.beginBackgroundTask(withName: "NitroSse-KeepAlive") {
|
|
73
78
|
self?.dispatcher.async {
|
|
@@ -93,7 +98,7 @@ class SseLifecycleManager {
|
|
|
93
98
|
}
|
|
94
99
|
#endif
|
|
95
100
|
}
|
|
96
|
-
|
|
101
|
+
|
|
97
102
|
/// Ends active `UIBackgroundTask` on the main queue and invalidates the task identifier.
|
|
98
103
|
func cleanupBackgroundTask() {
|
|
99
104
|
#if os(iOS)
|
|
@@ -107,7 +112,7 @@ class SseLifecycleManager {
|
|
|
107
112
|
}
|
|
108
113
|
#endif
|
|
109
114
|
}
|
|
110
|
-
|
|
115
|
+
|
|
111
116
|
@objc private func handleAppDidEnterBackground() {
|
|
112
117
|
dispatcher.async { [weak self] in
|
|
113
118
|
guard let self = self else { return }
|
|
@@ -115,7 +120,7 @@ class SseLifecycleManager {
|
|
|
115
120
|
self.onBackground()
|
|
116
121
|
}
|
|
117
122
|
}
|
|
118
|
-
|
|
123
|
+
|
|
119
124
|
@objc private func handleAppWillEnterForeground() {
|
|
120
125
|
dispatcher.async { [weak self] in
|
|
121
126
|
guard let self = self else { return }
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Value-type telemetry container tracking transport, parser, timing, and lifecycle metrics for `NitroSse`.
|
|
4
|
+
/// Access is serialized externally by `NitroSse` on its `SseDispatcher` queue.
|
|
5
|
+
internal struct SseMetrics {
|
|
6
|
+
// Transport metrics
|
|
7
|
+
private var rawBytesReceived: Double = 0
|
|
8
|
+
private var decompressedBytesReceived: Double?
|
|
9
|
+
private var sessionRawBytesBase: Double = 0
|
|
10
|
+
private var currentTaskRawBytes: Double = 0
|
|
11
|
+
private var sessionDecompressedBytesBase: Double = 0
|
|
12
|
+
private var currentTaskDecompressedBytes: Double = 0
|
|
13
|
+
private(set) var totalBytesReceived: Double = 0
|
|
14
|
+
private var chunksReceived: Double = 0
|
|
15
|
+
private var lastStatusCode: Double?
|
|
16
|
+
|
|
17
|
+
// Parser metrics
|
|
18
|
+
private var totalEventsReceived: Double = 0
|
|
19
|
+
private var commentsReceived: Double = 0
|
|
20
|
+
private var linesParsed: Double = 0
|
|
21
|
+
private var parseErrors: Double = 0
|
|
22
|
+
private var serverRetryDelayMs: Double?
|
|
23
|
+
|
|
24
|
+
// Timing metrics
|
|
25
|
+
private var connectedAt: Double?
|
|
26
|
+
private var connectionAttemptStartTime: Double?
|
|
27
|
+
private var timeToFirstByteMs: Double?
|
|
28
|
+
private var lastEventTime: Double?
|
|
29
|
+
private var lastHeartbeatTime: Double?
|
|
30
|
+
private var lastActivityTime: Double = 0
|
|
31
|
+
private var maxEventGapMs: Double = 0
|
|
32
|
+
|
|
33
|
+
// Lifecycle & error metrics
|
|
34
|
+
private var connectionAttempts: Double = 0
|
|
35
|
+
private var reconnectCount: Double = 0
|
|
36
|
+
private var lastReconnectDelayMs: Double?
|
|
37
|
+
private var disconnectReason: SseDisconnectReason?
|
|
38
|
+
private var lastErrorTime: Double?
|
|
39
|
+
private var lastErrorCode: String?
|
|
40
|
+
|
|
41
|
+
mutating func resetSessionByteCounters() {
|
|
42
|
+
sessionRawBytesBase = 0
|
|
43
|
+
currentTaskRawBytes = 0
|
|
44
|
+
sessionDecompressedBytesBase = 0
|
|
45
|
+
currentTaskDecompressedBytes = 0
|
|
46
|
+
rawBytesReceived = 0
|
|
47
|
+
decompressedBytesReceived = nil
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
mutating func recordConnectionAttemptStart(now: Double) {
|
|
51
|
+
connectionAttempts += 1
|
|
52
|
+
connectionAttemptStartTime = now
|
|
53
|
+
timeToFirstByteMs = nil
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
mutating func recordOpen(statusCode: Int, isReconnect: Bool, now: Double) {
|
|
57
|
+
if isReconnect {
|
|
58
|
+
reconnectCount += 1
|
|
59
|
+
}
|
|
60
|
+
lastStatusCode = Double(statusCode)
|
|
61
|
+
connectedAt = now
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
mutating func recordDataChunk(rawWireBytes: Int64, decompressedBytes: Int64?, now: Double) {
|
|
65
|
+
chunksReceived += 1
|
|
66
|
+
currentTaskRawBytes = Double(rawWireBytes)
|
|
67
|
+
rawBytesReceived = sessionRawBytesBase + currentTaskRawBytes
|
|
68
|
+
if let decomp = decompressedBytes {
|
|
69
|
+
currentTaskDecompressedBytes = Double(decomp)
|
|
70
|
+
decompressedBytesReceived = sessionDecompressedBytesBase + currentTaskDecompressedBytes
|
|
71
|
+
}
|
|
72
|
+
if timeToFirstByteMs == nil, let start = connectionAttemptStartTime {
|
|
73
|
+
timeToFirstByteMs = now - start
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
mutating func recordLinesParsed(_ count: Int) {
|
|
78
|
+
linesParsed += Double(count)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
mutating func recordParseError() {
|
|
82
|
+
parseErrors += 1
|
|
83
|
+
disconnectReason = .parserError
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
mutating func recordMessage(eventType: String, data: String, now: Double) {
|
|
87
|
+
let encodedDataSize = Double(data.utf8.count)
|
|
88
|
+
// WHATWG SSE accounting:
|
|
89
|
+
// - `message` is the default event type and is often omitted on the wire, so don't count it.
|
|
90
|
+
// - id byte accounting is handled when id: is encountered to avoid duplicate counting.
|
|
91
|
+
let eventTypeSize = (eventType.isEmpty || eventType == "message") ? 0.0 : Double(eventType.utf8.count)
|
|
92
|
+
totalBytesReceived += encodedDataSize + eventTypeSize
|
|
93
|
+
totalEventsReceived += 1
|
|
94
|
+
lastEventTime = now
|
|
95
|
+
recordActivity(now: now)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
mutating func recordComment(_ comment: String, now: Double) {
|
|
99
|
+
totalBytesReceived += Double(comment.utf8.count)
|
|
100
|
+
commentsReceived += 1
|
|
101
|
+
lastHeartbeatTime = now
|
|
102
|
+
recordActivity(now: now)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
mutating func recordServerRetryDelay(_ retryMs: Int64) {
|
|
106
|
+
serverRetryDelayMs = Double(retryMs)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
mutating func recordLastEventIdBytes(_ id: String) {
|
|
110
|
+
totalBytesReceived += Double(id.utf8.count)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
mutating func recordReconnectDelay(seconds: TimeInterval) {
|
|
114
|
+
lastReconnectDelayMs = seconds * 1000.0
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
mutating func recordUserStop() {
|
|
118
|
+
disconnectReason = .userStop
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
mutating func recordConnectionEnded() {
|
|
122
|
+
connectedAt = nil
|
|
123
|
+
flushTaskBytes()
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
mutating func recordFailure(
|
|
127
|
+
statusCode: Int?,
|
|
128
|
+
disconnectReason: SseDisconnectReason,
|
|
129
|
+
errorCode: String,
|
|
130
|
+
now: Double
|
|
131
|
+
) {
|
|
132
|
+
connectedAt = nil
|
|
133
|
+
flushTaskBytes()
|
|
134
|
+
if let statusCode = statusCode {
|
|
135
|
+
lastStatusCode = Double(statusCode)
|
|
136
|
+
}
|
|
137
|
+
self.disconnectReason = disconnectReason
|
|
138
|
+
lastErrorTime = now
|
|
139
|
+
lastErrorCode = errorCode
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
func toSseStats(eventBuffer: SseEventBuffer) -> SseStats {
|
|
143
|
+
return SseStats(
|
|
144
|
+
rawBytesReceived: rawBytesReceived,
|
|
145
|
+
decompressedBytesReceived: decompressedBytesReceived,
|
|
146
|
+
totalBytesReceived: totalBytesReceived,
|
|
147
|
+
chunksReceived: chunksReceived,
|
|
148
|
+
lastStatusCode: lastStatusCode,
|
|
149
|
+
totalEventsReceived: totalEventsReceived,
|
|
150
|
+
commentsReceived: commentsReceived,
|
|
151
|
+
linesParsed: linesParsed,
|
|
152
|
+
parseErrors: parseErrors,
|
|
153
|
+
serverRetryDelayMs: serverRetryDelayMs,
|
|
154
|
+
connectedAt: connectedAt,
|
|
155
|
+
timeToFirstByteMs: timeToFirstByteMs,
|
|
156
|
+
lastEventTime: lastEventTime,
|
|
157
|
+
lastHeartbeatTime: lastHeartbeatTime,
|
|
158
|
+
maxEventGapMs: maxEventGapMs,
|
|
159
|
+
eventsBuffered: Double(eventBuffer.eventsBuffered),
|
|
160
|
+
peakBufferedEvents: Double(eventBuffer.peakBufferedEvents),
|
|
161
|
+
bufferFlushCount: Double(eventBuffer.bufferFlushCount),
|
|
162
|
+
bufferOverflowCount: Double(eventBuffer.bufferOverflowCount),
|
|
163
|
+
connectionAttempts: connectionAttempts,
|
|
164
|
+
reconnectCount: reconnectCount,
|
|
165
|
+
lastReconnectDelayMs: lastReconnectDelayMs,
|
|
166
|
+
disconnectReason: disconnectReason,
|
|
167
|
+
lastErrorTime: lastErrorTime,
|
|
168
|
+
lastErrorCode: lastErrorCode
|
|
169
|
+
)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
private mutating func recordActivity(now: Double) {
|
|
173
|
+
if lastActivityTime > 0 {
|
|
174
|
+
let gap = now - lastActivityTime
|
|
175
|
+
if gap > maxEventGapMs {
|
|
176
|
+
maxEventGapMs = gap
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
lastActivityTime = now
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
private mutating func flushTaskBytes() {
|
|
183
|
+
sessionRawBytesBase += currentTaskRawBytes
|
|
184
|
+
currentTaskRawBytes = 0
|
|
185
|
+
sessionDecompressedBytesBase += currentTaskDecompressedBytes
|
|
186
|
+
currentTaskDecompressedBytes = 0
|
|
187
|
+
}
|
|
188
|
+
}
|
|
@@ -9,43 +9,49 @@ class SseNetworkMonitor {
|
|
|
9
9
|
_ interfaceChanged: Bool,
|
|
10
10
|
_ interfaceType: NWInterface.InterfaceType?
|
|
11
11
|
) -> Void
|
|
12
|
-
|
|
12
|
+
|
|
13
13
|
private var pathMonitor: NWPathMonitor?
|
|
14
14
|
private var lastPathInterface: NWInterface.InterfaceType?
|
|
15
15
|
private var monitorGeneration = 0
|
|
16
16
|
private let dispatcher: SseDispatcher
|
|
17
17
|
private let queue: DispatchQueue
|
|
18
18
|
private let onChange: NetworkChangeHandler
|
|
19
|
-
|
|
19
|
+
|
|
20
20
|
init(dispatcher: SseDispatcher, onChange: @escaping NetworkChangeHandler) {
|
|
21
21
|
self.dispatcher = dispatcher
|
|
22
22
|
// NWPathMonitor strictly requires a DispatchQueue instance for path callbacks.
|
|
23
23
|
self.queue = dispatcher.underlyingQueue ?? DispatchQueue(label: "com.nitrosse.networkmonitor.fallback")
|
|
24
24
|
self.onChange = onChange
|
|
25
25
|
}
|
|
26
|
-
|
|
26
|
+
|
|
27
27
|
/// Synchronously queries whether the active network path is currently satisfied (online).
|
|
28
28
|
var isPathSatisfied: Bool {
|
|
29
29
|
return pathMonitor?.currentPath.status == .satisfied
|
|
30
30
|
}
|
|
31
|
-
|
|
31
|
+
|
|
32
32
|
/// Starts observing system network changes. Idempotent call.
|
|
33
33
|
func start() {
|
|
34
34
|
guard pathMonitor == nil else { return }
|
|
35
|
-
|
|
35
|
+
|
|
36
36
|
monitorGeneration += 1
|
|
37
37
|
let generation = monitorGeneration
|
|
38
38
|
let monitor = NWPathMonitor()
|
|
39
39
|
monitor.pathUpdateHandler = { [weak self] path in
|
|
40
|
-
self
|
|
40
|
+
guard let self = self else { return }
|
|
41
|
+
let handleBlock = { [weak self] in
|
|
41
42
|
guard let self = self, self.monitorGeneration == generation else { return }
|
|
42
43
|
self.handlePathUpdate(path)
|
|
43
44
|
}
|
|
45
|
+
if self.dispatcher.isCurrentDispatcher() {
|
|
46
|
+
handleBlock()
|
|
47
|
+
} else {
|
|
48
|
+
self.dispatcher.async(handleBlock)
|
|
49
|
+
}
|
|
44
50
|
}
|
|
45
51
|
self.pathMonitor = monitor
|
|
46
52
|
monitor.start(queue: queue)
|
|
47
53
|
}
|
|
48
|
-
|
|
54
|
+
|
|
49
55
|
/// Cancels active path monitoring and releases resources.
|
|
50
56
|
func stop() {
|
|
51
57
|
monitorGeneration += 1
|
|
@@ -53,11 +59,11 @@ class SseNetworkMonitor {
|
|
|
53
59
|
pathMonitor = nil
|
|
54
60
|
lastPathInterface = nil
|
|
55
61
|
}
|
|
56
|
-
|
|
62
|
+
|
|
57
63
|
private func handlePathUpdate(_ path: NWPath) {
|
|
58
64
|
let isSatisfied = path.status == .satisfied
|
|
59
|
-
|
|
60
|
-
var interfaceType: NWInterface.InterfaceType?
|
|
65
|
+
|
|
66
|
+
var interfaceType: NWInterface.InterfaceType?
|
|
61
67
|
if path.usesInterfaceType(.wifi) {
|
|
62
68
|
interfaceType = .wifi
|
|
63
69
|
} else if path.usesInterfaceType(.cellular) {
|
|
@@ -67,9 +73,7 @@ class SseNetworkMonitor {
|
|
|
67
73
|
} else {
|
|
68
74
|
interfaceType = path.availableInterfaces.first?.type
|
|
69
75
|
}
|
|
70
|
-
|
|
71
|
-
print("[NitroSse] Network path changed: status=\(path.status), interface=\(String(describing: interfaceType))")
|
|
72
|
-
|
|
76
|
+
|
|
73
77
|
// Only trigger an interface change if both the previous and current interfaces are known and differ.
|
|
74
78
|
// Initial detection (lastPathInterface == nil) must NOT be flagged as an interface change to avoid
|
|
75
79
|
// falsely triggering an immediate stream restart right after connection startup.
|
|
@@ -84,7 +88,7 @@ class SseNetworkMonitor {
|
|
|
84
88
|
} else {
|
|
85
89
|
interfaceChanged = false
|
|
86
90
|
}
|
|
87
|
-
|
|
91
|
+
|
|
88
92
|
onChange(isSatisfied, interfaceChanged, interfaceType)
|
|
89
93
|
}
|
|
90
94
|
}
|