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
|
@@ -9,7 +9,11 @@ protocol SseConnectionDelegate: AnyObject {
|
|
|
9
9
|
func connectionDidReceiveRetry(retryMs: Int64, attemptVersion: Int)
|
|
10
10
|
func connectionDidFail(error: Error, response: HTTPURLResponse?, errorBody: String?, attemptVersion: Int)
|
|
11
11
|
func connectionDidUpdateLastEventId(id: String?, attemptVersion: Int)
|
|
12
|
-
func connectionDidReceiveDataChunk(
|
|
12
|
+
func connectionDidReceiveDataChunk(
|
|
13
|
+
rawWireBytes: Int64,
|
|
14
|
+
decompressedBytes: Int64?,
|
|
15
|
+
attemptVersion: Int
|
|
16
|
+
)
|
|
13
17
|
func connectionDidParseLines(count: Int, attemptVersion: Int)
|
|
14
18
|
func connectionDidEncounterParseError(attemptVersion: Int)
|
|
15
19
|
}
|
|
@@ -22,12 +26,16 @@ extension SseConnectionDelegate {
|
|
|
22
26
|
func connectionDidFail(error: Error, response: HTTPURLResponse?, attemptVersion: Int) {
|
|
23
27
|
connectionDidFail(error: error, response: response, errorBody: nil, attemptVersion: attemptVersion)
|
|
24
28
|
}
|
|
25
|
-
|
|
29
|
+
|
|
26
30
|
func connectionDidReceiveRetry(retryMs: Int64, attemptVersion: Int) {}
|
|
27
31
|
|
|
28
32
|
func connectionDidUpdateLastEventId(id: String?, attemptVersion: Int) {}
|
|
29
33
|
|
|
30
|
-
func connectionDidReceiveDataChunk(
|
|
34
|
+
func connectionDidReceiveDataChunk(
|
|
35
|
+
rawWireBytes: Int64,
|
|
36
|
+
decompressedBytes: Int64?,
|
|
37
|
+
attemptVersion: Int
|
|
38
|
+
) {}
|
|
31
39
|
|
|
32
40
|
func connectionDidParseLines(count: Int, attemptVersion: Int) {}
|
|
33
41
|
|
|
@@ -35,324 +43,25 @@ extension SseConnectionDelegate {
|
|
|
35
43
|
}
|
|
36
44
|
|
|
37
45
|
/// Maximum bytes to read from HTTP error responses to prevent Out-Of-Memory errors.
|
|
38
|
-
private let
|
|
39
|
-
|
|
40
|
-
/// Maximum bytes allowed for a single SSE line to prevent Out-Of-Memory errors.
|
|
41
|
-
private let MAX_SSE_LINE_LENGTH: Int = 16 * 1024 * 1024
|
|
42
|
-
|
|
43
|
-
/// Maximum bytes allowed for accumulated event data to prevent Out-Of-Memory errors.
|
|
44
|
-
private let MAX_SSE_EVENT_DATA_SIZE: Int = 16 * 1024 * 1024
|
|
46
|
+
private let maxErrorBodyBytes: Int = 8192
|
|
45
47
|
|
|
46
48
|
/// Protocol representing an active SSE connection that can be cancelled.
|
|
47
49
|
protocol SseEventSource: AnyObject {
|
|
48
50
|
func stop()
|
|
49
51
|
}
|
|
50
52
|
|
|
51
|
-
// MARK: - WHATWG SseEventParser
|
|
52
|
-
|
|
53
|
-
protocol SseEventParserDelegate: AnyObject {
|
|
54
|
-
func parserDidReceiveEvent(id: String?, type: String?, data: String)
|
|
55
|
-
func parserDidReceiveComment(_ comment: String)
|
|
56
|
-
func parserDidReceiveRetry(retryMs: Int64)
|
|
57
|
-
func parserDidUpdateLastEventId(_ id: String?)
|
|
58
|
-
func parserDidFail(error: Error)
|
|
59
|
-
func parserDidParseLines(_ count: Int)
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
extension SseEventParserDelegate {
|
|
63
|
-
func parserDidUpdateLastEventId(_ id: String?) {}
|
|
64
|
-
func parserDidFail(error: Error) {}
|
|
65
|
-
func parserDidParseLines(_ count: Int) {}
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/// Sequential streaming line-by-line SSE parser complying strictly with WHATWG Server-Sent Events specification.
|
|
69
|
-
/// Handles CR, LF, and CRLF line breaks, multi-line data concatenation, comments, IDs, and retry directives.
|
|
70
|
-
internal class SseEventParser {
|
|
71
|
-
weak var delegate: SseEventParserDelegate?
|
|
72
|
-
|
|
73
|
-
private var buffer = Data()
|
|
74
|
-
private var dataBuffer: String = ""
|
|
75
|
-
private var hasData: Bool = false
|
|
76
|
-
private var eventType: String? = nil
|
|
77
|
-
private var lastEventId: String? = nil
|
|
78
|
-
private var isAtStreamStart: Bool = true
|
|
79
|
-
|
|
80
|
-
init(initialLastEventId: String? = nil) {
|
|
81
|
-
self.lastEventId = initialLastEventId
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
func reset(initialLastEventId: String? = nil) {
|
|
85
|
-
buffer.removeAll()
|
|
86
|
-
dataBuffer = ""
|
|
87
|
-
hasData = false
|
|
88
|
-
eventType = nil
|
|
89
|
-
lastEventId = initialLastEventId
|
|
90
|
-
isAtStreamStart = true
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/// Flushes any pending data or un-terminated line when the stream reaches EOF.
|
|
94
|
-
/// Per WHATWG SSE specification: "Once the end of the file is reached, any pending data must be dispatched as an event."
|
|
95
|
-
func endOfStream() {
|
|
96
|
-
if !buffer.isEmpty {
|
|
97
|
-
if buffer.last == 0x0D {
|
|
98
|
-
buffer.removeLast()
|
|
99
|
-
}
|
|
100
|
-
let line = String(decoding: buffer, as: UTF8.self)
|
|
101
|
-
buffer.removeAll()
|
|
102
|
-
processLine(line)
|
|
103
|
-
delegate?.parserDidParseLines(1)
|
|
104
|
-
}
|
|
105
|
-
if hasData {
|
|
106
|
-
let eventData = dataBuffer
|
|
107
|
-
let id = lastEventId
|
|
108
|
-
let type = eventType
|
|
109
|
-
|
|
110
|
-
dataBuffer = ""
|
|
111
|
-
hasData = false
|
|
112
|
-
eventType = nil
|
|
113
|
-
|
|
114
|
-
delegate?.parserDidReceiveEvent(id: id, type: type, data: eventData)
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
func feed(data: Data) {
|
|
119
|
-
guard !data.isEmpty else { return }
|
|
120
|
-
var parsedLinesInChunk = 0
|
|
121
|
-
defer {
|
|
122
|
-
if parsedLinesInChunk > 0 {
|
|
123
|
-
delegate?.parserDidParseLines(parsedLinesInChunk)
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
var currentData = data
|
|
128
|
-
if isAtStreamStart {
|
|
129
|
-
if buffer.isEmpty && currentData.count >= 3 {
|
|
130
|
-
let sIdx = currentData.startIndex
|
|
131
|
-
if currentData[sIdx] == 0xEF && currentData[sIdx + 1] == 0xBB && currentData[sIdx + 2] == 0xBF {
|
|
132
|
-
currentData = currentData.subdata(in: (sIdx + 3)..<currentData.endIndex)
|
|
133
|
-
}
|
|
134
|
-
isAtStreamStart = false
|
|
135
|
-
} else {
|
|
136
|
-
let bom: [UInt8] = [0xEF, 0xBB, 0xBF]
|
|
137
|
-
buffer.append(currentData)
|
|
138
|
-
if buffer.count >= 3 {
|
|
139
|
-
if buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF {
|
|
140
|
-
buffer.removeSubrange(0..<3)
|
|
141
|
-
}
|
|
142
|
-
isAtStreamStart = false
|
|
143
|
-
currentData = buffer
|
|
144
|
-
buffer.removeAll()
|
|
145
|
-
} else {
|
|
146
|
-
for i in 0..<buffer.count {
|
|
147
|
-
if buffer[i] != bom[i] {
|
|
148
|
-
isAtStreamStart = false
|
|
149
|
-
currentData = buffer
|
|
150
|
-
buffer.removeAll()
|
|
151
|
-
break
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
if isAtStreamStart {
|
|
155
|
-
return
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
var readIndex = currentData.startIndex
|
|
162
|
-
let endIndex = currentData.endIndex
|
|
163
|
-
|
|
164
|
-
// If buffer has leftover bytes from previous chunks, handle line boundary first
|
|
165
|
-
if !buffer.isEmpty {
|
|
166
|
-
// Handle CR/CRLF split across chunk boundary
|
|
167
|
-
if buffer.last == 0x0D {
|
|
168
|
-
buffer.removeLast()
|
|
169
|
-
let line = String(decoding: buffer, as: UTF8.self)
|
|
170
|
-
buffer.removeAll()
|
|
171
|
-
processLine(line)
|
|
172
|
-
parsedLinesInChunk += 1
|
|
173
|
-
if currentData.first == 0x0A {
|
|
174
|
-
readIndex = currentData.startIndex + 1
|
|
175
|
-
}
|
|
176
|
-
} else if let firstLine = findNextLine(in: currentData, from: readIndex) {
|
|
177
|
-
if buffer.count + firstLine.content.count > MAX_SSE_LINE_LENGTH {
|
|
178
|
-
let error = NSError(domain: "NitroSse", code: -2002, userInfo: [NSLocalizedDescriptionKey: "SSE line exceeded maximum limit of \(MAX_SSE_LINE_LENGTH) bytes"])
|
|
179
|
-
delegate?.parserDidFail(error: error)
|
|
180
|
-
buffer.removeAll()
|
|
181
|
-
return
|
|
182
|
-
}
|
|
183
|
-
buffer.append(currentData.subdata(in: firstLine.content))
|
|
184
|
-
let line = String(decoding: buffer, as: UTF8.self)
|
|
185
|
-
buffer.removeAll()
|
|
186
|
-
processLine(line)
|
|
187
|
-
parsedLinesInChunk += 1
|
|
188
|
-
readIndex = firstLine.nextIndex
|
|
189
|
-
} else {
|
|
190
|
-
// currentData has no line ending: append chunk to buffer if within limit
|
|
191
|
-
if buffer.count + currentData.count > MAX_SSE_LINE_LENGTH {
|
|
192
|
-
let error = NSError(domain: "NitroSse", code: -2002, userInfo: [NSLocalizedDescriptionKey: "SSE line exceeded maximum limit of \(MAX_SSE_LINE_LENGTH) bytes"])
|
|
193
|
-
delegate?.parserDidFail(error: error)
|
|
194
|
-
buffer.removeAll()
|
|
195
|
-
return
|
|
196
|
-
}
|
|
197
|
-
buffer.append(currentData)
|
|
198
|
-
return
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
// Scan remaining lines directly from currentData without buffering full chunk
|
|
203
|
-
while readIndex < endIndex {
|
|
204
|
-
guard let lineRange = findNextLine(in: currentData, from: readIndex) else {
|
|
205
|
-
break
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
if lineRange.content.count > MAX_SSE_LINE_LENGTH {
|
|
209
|
-
let error = NSError(domain: "NitroSse", code: -2002, userInfo: [NSLocalizedDescriptionKey: "SSE line exceeded maximum limit of \(MAX_SSE_LINE_LENGTH) bytes"])
|
|
210
|
-
delegate?.parserDidFail(error: error)
|
|
211
|
-
buffer.removeAll()
|
|
212
|
-
return
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
let lineData = currentData.subdata(in: lineRange.content)
|
|
216
|
-
readIndex = lineRange.nextIndex
|
|
217
|
-
|
|
218
|
-
let line = String(decoding: lineData, as: UTF8.self)
|
|
219
|
-
processLine(line)
|
|
220
|
-
parsedLinesInChunk += 1
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
// Save trailing incomplete line fragment into buffer
|
|
224
|
-
if readIndex < endIndex {
|
|
225
|
-
let trailingData = currentData.subdata(in: readIndex..<endIndex)
|
|
226
|
-
if buffer.count + trailingData.count > MAX_SSE_LINE_LENGTH {
|
|
227
|
-
let error = NSError(domain: "NitroSse", code: -2002, userInfo: [NSLocalizedDescriptionKey: "SSE line exceeded maximum limit of \(MAX_SSE_LINE_LENGTH) bytes"])
|
|
228
|
-
delegate?.parserDidFail(error: error)
|
|
229
|
-
buffer.removeAll()
|
|
230
|
-
return
|
|
231
|
-
}
|
|
232
|
-
buffer.append(trailingData)
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
private struct LineRange {
|
|
237
|
-
let content: Range<Int>
|
|
238
|
-
let nextIndex: Int
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
/// Finds next line in data from startIndex handling \r\n, \r, and \n.
|
|
242
|
-
/// If data ends with \r at the very end, returns nil to defer until next chunk so \r\n can be resolved.
|
|
243
|
-
private func findNextLine(in data: Data, from startIndex: Int) -> LineRange? {
|
|
244
|
-
let endIndex = data.endIndex
|
|
245
|
-
guard startIndex < endIndex else { return nil }
|
|
246
|
-
|
|
247
|
-
var index = startIndex
|
|
248
|
-
while index < endIndex {
|
|
249
|
-
let byte = data[index]
|
|
250
|
-
if byte == 0x0A { // \n (LF)
|
|
251
|
-
return LineRange(content: startIndex..<index, nextIndex: index + 1)
|
|
252
|
-
} else if byte == 0x0D { // \r (CR)
|
|
253
|
-
if index + 1 < endIndex {
|
|
254
|
-
if data[index + 1] == 0x0A { // \r\n (CRLF)
|
|
255
|
-
return LineRange(content: startIndex..<index, nextIndex: index + 2)
|
|
256
|
-
} else { // Single \r
|
|
257
|
-
return LineRange(content: startIndex..<index, nextIndex: index + 1)
|
|
258
|
-
}
|
|
259
|
-
} else {
|
|
260
|
-
// Buffer ends with \r; wait for next chunk to verify if it is \r\n
|
|
261
|
-
return nil
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
index += 1
|
|
265
|
-
}
|
|
266
|
-
return nil
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
private func processLine(_ line: String) {
|
|
270
|
-
if line.isEmpty {
|
|
271
|
-
// Empty line dispatches the current event per WHATWG specification
|
|
272
|
-
if hasData {
|
|
273
|
-
let eventData = dataBuffer
|
|
274
|
-
let id = lastEventId
|
|
275
|
-
let type = eventType
|
|
276
|
-
|
|
277
|
-
dataBuffer = ""
|
|
278
|
-
hasData = false
|
|
279
|
-
eventType = nil
|
|
280
|
-
|
|
281
|
-
delegate?.parserDidReceiveEvent(id: id, type: type, data: eventData)
|
|
282
|
-
}
|
|
283
|
-
return
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
if line.hasPrefix(":") {
|
|
287
|
-
// WHATWG SSE: Lines starting with ':' are comments (often used for keepalive/heartbeat).
|
|
288
|
-
// Normalizes comment by removing only a single leading space per WHATWG SSE specification.
|
|
289
|
-
let rawComment = String(line.dropFirst())
|
|
290
|
-
let comment = rawComment.hasPrefix(" ") ? String(rawComment.dropFirst()) : rawComment
|
|
291
|
-
delegate?.parserDidReceiveComment(comment)
|
|
292
|
-
return
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
let colonIndex = line.firstIndex(of: ":")
|
|
296
|
-
let field: String
|
|
297
|
-
var value: String
|
|
298
|
-
|
|
299
|
-
if let colon = colonIndex {
|
|
300
|
-
field = String(line[..<colon])
|
|
301
|
-
let rawValue = String(line[line.index(after: colon)...])
|
|
302
|
-
value = rawValue.hasPrefix(" ") ? String(rawValue.dropFirst()) : rawValue
|
|
303
|
-
} else {
|
|
304
|
-
field = line
|
|
305
|
-
value = ""
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
switch field {
|
|
309
|
-
case "data":
|
|
310
|
-
let separatorSize = hasData ? 1 : 0
|
|
311
|
-
if dataBuffer.utf8.count + separatorSize + value.utf8.count > MAX_SSE_EVENT_DATA_SIZE {
|
|
312
|
-
let error = NSError(domain: "NitroSse", code: -2003, userInfo: [NSLocalizedDescriptionKey: "SSE event data exceeded maximum limit of \(MAX_SSE_EVENT_DATA_SIZE) bytes"])
|
|
313
|
-
delegate?.parserDidFail(error: error)
|
|
314
|
-
dataBuffer = ""
|
|
315
|
-
hasData = false
|
|
316
|
-
return
|
|
317
|
-
}
|
|
318
|
-
if hasData {
|
|
319
|
-
dataBuffer.append("\n")
|
|
320
|
-
dataBuffer.append(value)
|
|
321
|
-
} else {
|
|
322
|
-
dataBuffer = value
|
|
323
|
-
hasData = true
|
|
324
|
-
}
|
|
325
|
-
case "id":
|
|
326
|
-
// WHATWG: If field value contains a U+0000 NULL character, the field must be ignored.
|
|
327
|
-
if !value.contains("\0") {
|
|
328
|
-
lastEventId = value.isEmpty ? nil : value
|
|
329
|
-
delegate?.parserDidUpdateLastEventId(lastEventId)
|
|
330
|
-
}
|
|
331
|
-
case "event":
|
|
332
|
-
eventType = value.isEmpty ? nil : value
|
|
333
|
-
case "retry":
|
|
334
|
-
if !value.isEmpty && value.allSatisfy({ $0.isASCII && $0.isNumber }), let retryVal = Int64(value), retryVal >= 0 {
|
|
335
|
-
delegate?.parserDidReceiveRetry(retryMs: retryVal)
|
|
336
|
-
}
|
|
337
|
-
default:
|
|
338
|
-
// Unrecognized fields are ignored per WHATWG specification
|
|
339
|
-
break
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
|
|
344
53
|
// MARK: - RealSseEventSource
|
|
345
54
|
|
|
346
55
|
/// Native EventSource implementation backed by Apple Foundation `URLSession` and `URLSessionDataDelegate`.
|
|
347
|
-
internal class RealSseEventSource: NSObject,
|
|
56
|
+
internal class RealSseEventSource: NSObject, SseEventSource {
|
|
348
57
|
private weak var delegate: SseConnectionDelegate?
|
|
349
58
|
private let attemptVersion: Int
|
|
350
59
|
private let dispatcher: SseDispatcher
|
|
351
|
-
|
|
60
|
+
|
|
352
61
|
private var session: URLSession?
|
|
353
62
|
private var task: URLSessionDataTask?
|
|
354
63
|
private let parser: SseEventParser
|
|
355
|
-
|
|
64
|
+
|
|
356
65
|
private var didReceiveValidResponse: Bool = false
|
|
357
66
|
private var isFinished: Bool = false
|
|
358
67
|
private var isTerminalDispatched: Bool = false
|
|
@@ -361,10 +70,16 @@ internal class RealSseEventSource: NSObject, URLSessionDataDelegate, SseEventSou
|
|
|
361
70
|
private var isGzip: Bool = false
|
|
362
71
|
private var decompressedBytesReceived: Int64 = 0
|
|
363
72
|
private var isCollectingErrorBody: Bool = false
|
|
73
|
+
private var hasConnectionTimer: Bool = false
|
|
364
74
|
private var errorBodyData = Data()
|
|
365
75
|
private var pendingErrorResponse: HTTPURLResponse?
|
|
366
|
-
|
|
367
|
-
init(
|
|
76
|
+
|
|
77
|
+
init(
|
|
78
|
+
delegate: SseConnectionDelegate,
|
|
79
|
+
attemptVersion: Int,
|
|
80
|
+
dispatcher: SseDispatcher,
|
|
81
|
+
initialLastEventId: String? = nil
|
|
82
|
+
) {
|
|
368
83
|
self.delegate = delegate
|
|
369
84
|
self.attemptVersion = attemptVersion
|
|
370
85
|
self.dispatcher = dispatcher
|
|
@@ -372,7 +87,7 @@ internal class RealSseEventSource: NSObject, URLSessionDataDelegate, SseEventSou
|
|
|
372
87
|
super.init()
|
|
373
88
|
self.parser.delegate = self
|
|
374
89
|
}
|
|
375
|
-
|
|
90
|
+
|
|
376
91
|
func start(
|
|
377
92
|
request: URLRequest,
|
|
378
93
|
sessionConfig: URLSessionConfiguration,
|
|
@@ -381,19 +96,19 @@ internal class RealSseEventSource: NSObject, URLSessionDataDelegate, SseEventSou
|
|
|
381
96
|
let queue = OperationQueue()
|
|
382
97
|
queue.maxConcurrentOperationCount = 1
|
|
383
98
|
queue.name = "com.margelo.nitro.sse.urlsession"
|
|
384
|
-
|
|
99
|
+
|
|
385
100
|
let session = URLSession(configuration: sessionConfig, delegate: self, delegateQueue: queue)
|
|
386
101
|
self.session = session
|
|
387
|
-
|
|
102
|
+
|
|
388
103
|
let task = session.dataTask(with: request)
|
|
389
104
|
self.task = task
|
|
390
|
-
|
|
105
|
+
|
|
391
106
|
if connectionTimeout > 0 {
|
|
392
107
|
startConnectionTimer(timeout: connectionTimeout)
|
|
393
108
|
}
|
|
394
109
|
task.resume()
|
|
395
110
|
}
|
|
396
|
-
|
|
111
|
+
|
|
397
112
|
func stop() {
|
|
398
113
|
dispatcher.async { [weak self] in
|
|
399
114
|
guard let self = self, !self.isCancelled else { return }
|
|
@@ -402,7 +117,18 @@ internal class RealSseEventSource: NSObject, URLSessionDataDelegate, SseEventSou
|
|
|
402
117
|
self.cleanupTransport()
|
|
403
118
|
}
|
|
404
119
|
}
|
|
405
|
-
|
|
120
|
+
|
|
121
|
+
private static func decodeErrorBody(_ data: Data) -> String? {
|
|
122
|
+
guard !data.isEmpty else { return nil }
|
|
123
|
+
// WHATWG SSE Section 9.2.2: invalid UTF-8 bytes must be replaced with U+FFFD, not dropped.
|
|
124
|
+
// swiftlint:disable:next optional_data_string_conversion
|
|
125
|
+
var decoded = String(decoding: data, as: UTF8.self)
|
|
126
|
+
if decoded.hasPrefix("\u{FEFF}") {
|
|
127
|
+
decoded.removeFirst()
|
|
128
|
+
}
|
|
129
|
+
return decoded.isEmpty ? nil : decoded
|
|
130
|
+
}
|
|
131
|
+
|
|
406
132
|
private func cleanupTransport() {
|
|
407
133
|
dispatcher.assertOnQueue()
|
|
408
134
|
task?.cancel()
|
|
@@ -410,12 +136,23 @@ internal class RealSseEventSource: NSObject, URLSessionDataDelegate, SseEventSou
|
|
|
410
136
|
task = nil
|
|
411
137
|
session = nil
|
|
412
138
|
}
|
|
413
|
-
|
|
139
|
+
|
|
414
140
|
private func startConnectionTimer(timeout: TimeInterval) {
|
|
415
|
-
|
|
141
|
+
hasConnectionTimer = true
|
|
416
142
|
dispatcher.asyncAfter(delay: timeout) { [weak self] in
|
|
417
143
|
guard let self = self, !self.didReceiveValidResponse, !self.isFinished, !self.isCancelled else { return }
|
|
418
144
|
self.isFinished = true
|
|
145
|
+
if self.isCollectingErrorBody, let resp = self.pendingErrorResponse {
|
|
146
|
+
self.isCollectingErrorBody = false
|
|
147
|
+
let error = NSError(
|
|
148
|
+
domain: "NitroSse",
|
|
149
|
+
code: resp.statusCode,
|
|
150
|
+
userInfo: [NSLocalizedDescriptionKey: "HTTP \(resp.statusCode)"]
|
|
151
|
+
)
|
|
152
|
+
let bodyString = Self.decodeErrorBody(self.errorBodyData)
|
|
153
|
+
self.dispatchTerminalFailure(error: error, response: resp, errorBody: bodyString)
|
|
154
|
+
return
|
|
155
|
+
}
|
|
419
156
|
let error = NSError(
|
|
420
157
|
domain: NSURLErrorDomain,
|
|
421
158
|
code: NSURLErrorTimedOut,
|
|
@@ -424,13 +161,103 @@ internal class RealSseEventSource: NSObject, URLSessionDataDelegate, SseEventSou
|
|
|
424
161
|
self.dispatchTerminalFailure(error: error, response: nil, errorBody: nil)
|
|
425
162
|
}
|
|
426
163
|
}
|
|
427
|
-
|
|
428
|
-
// MARK: - URLSessionTaskDelegate & URLSessionDataDelegate
|
|
429
164
|
|
|
165
|
+
private func dispatchTerminalFailure(error: Error, response: HTTPURLResponse?, errorBody: String? = nil) {
|
|
166
|
+
guard !isTerminalDispatched else { return }
|
|
167
|
+
isTerminalDispatched = true
|
|
168
|
+
isFinished = true
|
|
169
|
+
cleanupTransport()
|
|
170
|
+
delegate?.connectionDidFail(
|
|
171
|
+
error: error,
|
|
172
|
+
response: response,
|
|
173
|
+
errorBody: errorBody,
|
|
174
|
+
attemptVersion: attemptVersion
|
|
175
|
+
)
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// MARK: - URLSessionDataDelegate
|
|
180
|
+
|
|
181
|
+
extension RealSseEventSource: URLSessionDataDelegate {
|
|
430
182
|
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
|
|
431
183
|
// Delegate callback confirming invalidation of the session and its delegate retain cycle.
|
|
432
184
|
}
|
|
433
|
-
|
|
185
|
+
|
|
186
|
+
private func handleNonOkResponse(
|
|
187
|
+
_ httpResponse: HTTPURLResponse,
|
|
188
|
+
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void
|
|
189
|
+
) {
|
|
190
|
+
let statusCode = httpResponse.statusCode
|
|
191
|
+
// WHATWG EventSource Section 7: HTTP 204 No Content explicitly fails connection and halts reconnection
|
|
192
|
+
if statusCode == 204 {
|
|
193
|
+
let error = NSError(
|
|
194
|
+
domain: "NitroSse",
|
|
195
|
+
code: 204,
|
|
196
|
+
userInfo: [NSLocalizedDescriptionKey: "HTTP 204 No Content"]
|
|
197
|
+
)
|
|
198
|
+
self.dispatchTerminalFailure(error: error, response: httpResponse, errorBody: nil)
|
|
199
|
+
completionHandler(.cancel)
|
|
200
|
+
return
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if statusCode < 400 || httpResponse.expectedContentLength == 0 {
|
|
204
|
+
let error = NSError(
|
|
205
|
+
domain: "NitroSse",
|
|
206
|
+
code: statusCode,
|
|
207
|
+
userInfo: [NSLocalizedDescriptionKey: "HTTP \(statusCode)"]
|
|
208
|
+
)
|
|
209
|
+
self.dispatchTerminalFailure(error: error, response: httpResponse, errorBody: nil)
|
|
210
|
+
completionHandler(.cancel)
|
|
211
|
+
return
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
self.isCollectingErrorBody = true
|
|
215
|
+
self.pendingErrorResponse = httpResponse
|
|
216
|
+
self.errorBodyData.removeAll()
|
|
217
|
+
if !self.hasConnectionTimer {
|
|
218
|
+
self.startConnectionTimer(timeout: 15.0)
|
|
219
|
+
}
|
|
220
|
+
completionHandler(.allow)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
private func handleHttpResponse(
|
|
224
|
+
_ httpResponse: HTTPURLResponse,
|
|
225
|
+
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void
|
|
226
|
+
) {
|
|
227
|
+
self.lastResponse = httpResponse
|
|
228
|
+
guard httpResponse.statusCode == 200 else {
|
|
229
|
+
handleNonOkResponse(httpResponse, completionHandler: completionHandler)
|
|
230
|
+
return
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// Validate Content-Type: exact MIME type before parameters must match text/event-stream
|
|
234
|
+
let contentType = httpResponse.value(forHTTPHeaderField: "Content-Type") ??
|
|
235
|
+
(httpResponse.allHeaderFields["Content-Type"] as? String) ?? ""
|
|
236
|
+
guard SseFailureClassifier.isEventStreamMimeType(contentType) else {
|
|
237
|
+
let error = NSError(
|
|
238
|
+
domain: "NitroSse",
|
|
239
|
+
code: -2001,
|
|
240
|
+
userInfo: [
|
|
241
|
+
NSLocalizedDescriptionKey:
|
|
242
|
+
"Invalid Content-Type: expected text/event-stream but received '\(contentType)'"
|
|
243
|
+
]
|
|
244
|
+
)
|
|
245
|
+
self.dispatchTerminalFailure(error: error, response: httpResponse, errorBody: nil)
|
|
246
|
+
completionHandler(.cancel)
|
|
247
|
+
return
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
let contentEncoding = httpResponse.value(forHTTPHeaderField: "Content-Encoding") ??
|
|
251
|
+
(httpResponse.allHeaderFields["Content-Encoding"] as? String) ?? ""
|
|
252
|
+
if contentEncoding.lowercased().contains("gzip") {
|
|
253
|
+
self.isGzip = true
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
self.didReceiveValidResponse = true
|
|
257
|
+
self.delegate?.connectionDidOpen(response: httpResponse, attemptVersion: self.attemptVersion)
|
|
258
|
+
completionHandler(.allow)
|
|
259
|
+
}
|
|
260
|
+
|
|
434
261
|
func urlSession(
|
|
435
262
|
_ session: URLSession,
|
|
436
263
|
dataTask: URLSessionDataTask,
|
|
@@ -438,106 +265,56 @@ internal class RealSseEventSource: NSObject, URLSessionDataDelegate, SseEventSou
|
|
|
438
265
|
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void
|
|
439
266
|
) {
|
|
440
267
|
dispatcher.async { [weak self] in
|
|
441
|
-
guard let self = self, !self.isCancelled else {
|
|
268
|
+
guard let self = self, !self.isCancelled, !self.isTerminalDispatched else {
|
|
442
269
|
completionHandler(.cancel)
|
|
443
270
|
return
|
|
444
271
|
}
|
|
445
|
-
|
|
272
|
+
|
|
446
273
|
guard let httpResponse = response as? HTTPURLResponse else {
|
|
447
|
-
let error = NSError(domain: "NitroSse", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid non-HTTP response"])
|
|
448
|
-
self.isFinished = true
|
|
449
|
-
self.dispatchTerminalFailure(error: error, response: nil, errorBody: nil)
|
|
450
|
-
completionHandler(.cancel)
|
|
451
|
-
return
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
self.lastResponse = httpResponse
|
|
455
|
-
let statusCode = httpResponse.statusCode
|
|
456
|
-
|
|
457
|
-
// WHATWG EventSource Section 7: HTTP 204 No Content explicitly fails connection and halts reconnection
|
|
458
|
-
if statusCode == 204 {
|
|
459
274
|
let error = NSError(
|
|
460
275
|
domain: "NitroSse",
|
|
461
|
-
code:
|
|
462
|
-
userInfo: [NSLocalizedDescriptionKey: "HTTP
|
|
276
|
+
code: -1,
|
|
277
|
+
userInfo: [NSLocalizedDescriptionKey: "Invalid non-HTTP response"]
|
|
463
278
|
)
|
|
464
|
-
self.
|
|
465
|
-
self.dispatchTerminalFailure(error: error, response: httpResponse, errorBody: nil)
|
|
279
|
+
self.dispatchTerminalFailure(error: error, response: nil, errorBody: nil)
|
|
466
280
|
completionHandler(.cancel)
|
|
467
281
|
return
|
|
468
282
|
}
|
|
469
|
-
|
|
470
|
-
// Validate HTTP Status Code (Collect bounded body if statusCode is not 200)
|
|
471
|
-
guard statusCode == 200 else {
|
|
472
|
-
self.isFinished = true
|
|
473
|
-
if httpResponse.expectedContentLength == 0 {
|
|
474
|
-
let error = NSError(domain: "NitroSse", code: statusCode, userInfo: [NSLocalizedDescriptionKey: "HTTP \(statusCode)"])
|
|
475
|
-
self.dispatchTerminalFailure(error: error, response: httpResponse, errorBody: nil)
|
|
476
|
-
completionHandler(.cancel)
|
|
477
|
-
return
|
|
478
|
-
}
|
|
479
283
|
|
|
480
|
-
|
|
481
|
-
self.pendingErrorResponse = httpResponse
|
|
482
|
-
self.errorBodyData.removeAll()
|
|
483
|
-
completionHandler(.allow)
|
|
484
|
-
return
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
// Validate Content-Type: exact MIME type before parameters must match text/event-stream
|
|
488
|
-
let contentType = httpResponse.value(forHTTPHeaderField: "Content-Type") ??
|
|
489
|
-
(httpResponse.allHeaderFields["Content-Type"] as? String) ?? ""
|
|
490
|
-
let mimeType = contentType.split(separator: ";").first?.trimmingCharacters(in: .whitespaces).lowercased() ?? ""
|
|
491
|
-
guard mimeType == "text/event-stream" else {
|
|
492
|
-
let error = NSError(
|
|
493
|
-
domain: "NitroSse",
|
|
494
|
-
code: -2001,
|
|
495
|
-
userInfo: [NSLocalizedDescriptionKey: "Invalid Content-Type: expected text/event-stream but received '\(contentType)'"]
|
|
496
|
-
)
|
|
497
|
-
self.isFinished = true
|
|
498
|
-
self.dispatchTerminalFailure(error: error, response: httpResponse, errorBody: nil)
|
|
499
|
-
completionHandler(.cancel)
|
|
500
|
-
return
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
let contentEncoding = httpResponse.value(forHTTPHeaderField: "Content-Encoding") ??
|
|
504
|
-
(httpResponse.allHeaderFields["Content-Encoding"] as? String) ?? ""
|
|
505
|
-
if contentEncoding.lowercased().contains("gzip") {
|
|
506
|
-
self.isGzip = true
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
self.didReceiveValidResponse = true
|
|
510
|
-
self.delegate?.connectionDidOpen(response: httpResponse, attemptVersion: self.attemptVersion)
|
|
511
|
-
completionHandler(.allow)
|
|
284
|
+
self.handleHttpResponse(httpResponse, completionHandler: completionHandler)
|
|
512
285
|
}
|
|
513
286
|
}
|
|
514
|
-
|
|
287
|
+
|
|
515
288
|
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
|
|
516
289
|
dispatcher.async { [weak self] in
|
|
517
290
|
guard let self = self, !self.isCancelled, !self.isTerminalDispatched else { return }
|
|
518
291
|
if self.isCollectingErrorBody {
|
|
519
|
-
let remaining =
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
self.errorBodyData.append(chunk)
|
|
523
|
-
}
|
|
524
|
-
if self.errorBodyData.count >= MAX_ERROR_BODY_BYTES {
|
|
292
|
+
let remaining = maxErrorBodyBytes - self.errorBodyData.count
|
|
293
|
+
self.errorBodyData.append(data.prefix(remaining))
|
|
294
|
+
if self.errorBodyData.count >= maxErrorBodyBytes {
|
|
525
295
|
self.isCollectingErrorBody = false
|
|
526
|
-
let resp = self.pendingErrorResponse
|
|
296
|
+
let resp = self.pendingErrorResponse
|
|
527
297
|
let statusCode = resp?.statusCode ?? 500
|
|
528
|
-
let error = NSError(
|
|
529
|
-
|
|
298
|
+
let error = NSError(
|
|
299
|
+
domain: "NitroSse",
|
|
300
|
+
code: statusCode,
|
|
301
|
+
userInfo: [NSLocalizedDescriptionKey: "HTTP \(statusCode)"]
|
|
302
|
+
)
|
|
303
|
+
let bodyString = Self.decodeErrorBody(self.errorBodyData)
|
|
530
304
|
self.dispatchTerminalFailure(error: error, response: resp, errorBody: bodyString)
|
|
531
305
|
}
|
|
532
306
|
return
|
|
533
307
|
}
|
|
534
308
|
self.decompressedBytesReceived += Int64(data.count)
|
|
535
|
-
let rawBytesCount = dataTask.countOfBytesReceived > 0
|
|
536
|
-
|
|
309
|
+
let rawBytesCount = dataTask.countOfBytesReceived > 0
|
|
310
|
+
? dataTask.countOfBytesReceived
|
|
311
|
+
: self.decompressedBytesReceived
|
|
312
|
+
if !self.isGzip &&
|
|
313
|
+
dataTask.countOfBytesReceived > 0 &&
|
|
314
|
+
self.decompressedBytesReceived > dataTask.countOfBytesReceived {
|
|
537
315
|
self.isGzip = true
|
|
538
316
|
}
|
|
539
317
|
self.delegate?.connectionDidReceiveDataChunk(
|
|
540
|
-
chunkLength: data.count,
|
|
541
318
|
rawWireBytes: rawBytesCount,
|
|
542
319
|
decompressedBytes: self.isGzip ? self.decompressedBytesReceived : nil,
|
|
543
320
|
attemptVersion: self.attemptVersion
|
|
@@ -545,22 +322,26 @@ internal class RealSseEventSource: NSObject, URLSessionDataDelegate, SseEventSou
|
|
|
545
322
|
self.parser.feed(data: data)
|
|
546
323
|
}
|
|
547
324
|
}
|
|
548
|
-
|
|
325
|
+
|
|
549
326
|
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
|
|
550
327
|
dispatcher.async { [weak self] in
|
|
551
328
|
guard let self = self, !self.isCancelled else { return }
|
|
552
329
|
self.isFinished = true
|
|
553
|
-
|
|
330
|
+
|
|
554
331
|
if self.isCollectingErrorBody {
|
|
555
332
|
self.isCollectingErrorBody = false
|
|
556
|
-
let resp = self.pendingErrorResponse
|
|
333
|
+
let resp = self.pendingErrorResponse
|
|
557
334
|
let statusCode = resp?.statusCode ?? 500
|
|
558
|
-
let finalError = error ?? NSError(
|
|
559
|
-
|
|
335
|
+
let finalError = error ?? NSError(
|
|
336
|
+
domain: "NitroSse",
|
|
337
|
+
code: statusCode,
|
|
338
|
+
userInfo: [NSLocalizedDescriptionKey: "HTTP \(statusCode)"]
|
|
339
|
+
)
|
|
340
|
+
let bodyString = Self.decodeErrorBody(self.errorBodyData)
|
|
560
341
|
self.dispatchTerminalFailure(error: finalError, response: resp, errorBody: bodyString)
|
|
561
342
|
return
|
|
562
343
|
}
|
|
563
|
-
|
|
344
|
+
|
|
564
345
|
if let error = error {
|
|
565
346
|
let nsError = error as NSError
|
|
566
347
|
if nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorCancelled {
|
|
@@ -571,24 +352,18 @@ internal class RealSseEventSource: NSObject, URLSessionDataDelegate, SseEventSou
|
|
|
571
352
|
self.dispatchTerminalFailure(error: error, response: self.lastResponse, errorBody: nil)
|
|
572
353
|
} else {
|
|
573
354
|
guard !self.isTerminalDispatched else { return }
|
|
574
|
-
self.isTerminalDispatched = true
|
|
575
355
|
self.parser.endOfStream()
|
|
356
|
+
self.isTerminalDispatched = true
|
|
576
357
|
self.cleanupTransport()
|
|
577
358
|
self.delegate?.connectionDidClose(attemptVersion: self.attemptVersion)
|
|
578
359
|
}
|
|
579
360
|
}
|
|
580
361
|
}
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
cleanupTransport()
|
|
587
|
-
delegate?.connectionDidFail(error: error, response: response, errorBody: errorBody, attemptVersion: attemptVersion)
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
// MARK: - SseEventParserDelegate
|
|
591
|
-
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// MARK: - SseEventParserDelegate
|
|
365
|
+
|
|
366
|
+
extension RealSseEventSource: SseEventParserDelegate {
|
|
592
367
|
func parserDidReceiveEvent(id: String?, type: String?, data: String) {
|
|
593
368
|
dispatcher.assertOnQueue()
|
|
594
369
|
guard !isCancelled, !isTerminalDispatched else { return }
|
|
@@ -599,25 +374,25 @@ internal class RealSseEventSource: NSObject, URLSessionDataDelegate, SseEventSou
|
|
|
599
374
|
attemptVersion: attemptVersion
|
|
600
375
|
)
|
|
601
376
|
}
|
|
602
|
-
|
|
377
|
+
|
|
603
378
|
func parserDidReceiveComment(_ comment: String) {
|
|
604
379
|
dispatcher.assertOnQueue()
|
|
605
380
|
guard !isCancelled, !isTerminalDispatched else { return }
|
|
606
381
|
delegate?.connectionDidReceiveComment(comment, attemptVersion: attemptVersion)
|
|
607
382
|
}
|
|
608
|
-
|
|
383
|
+
|
|
609
384
|
func parserDidReceiveRetry(retryMs: Int64) {
|
|
610
385
|
dispatcher.assertOnQueue()
|
|
611
386
|
guard !isCancelled, !isTerminalDispatched else { return }
|
|
612
387
|
delegate?.connectionDidReceiveRetry(retryMs: retryMs, attemptVersion: attemptVersion)
|
|
613
388
|
}
|
|
614
|
-
|
|
389
|
+
|
|
615
390
|
func parserDidUpdateLastEventId(_ id: String?) {
|
|
616
391
|
dispatcher.assertOnQueue()
|
|
617
392
|
guard !isCancelled, !isTerminalDispatched else { return }
|
|
618
393
|
delegate?.connectionDidUpdateLastEventId(id: id, attemptVersion: attemptVersion)
|
|
619
394
|
}
|
|
620
|
-
|
|
395
|
+
|
|
621
396
|
func parserDidParseLines(_ count: Int) {
|
|
622
397
|
dispatcher.assertOnQueue()
|
|
623
398
|
guard !isCancelled, !isTerminalDispatched else { return }
|
|
@@ -636,62 +411,79 @@ internal class RealSseEventSource: NSObject, URLSessionDataDelegate, SseEventSou
|
|
|
636
411
|
|
|
637
412
|
/// Factory creating native `RealSseEventSource` instances configured with custom timeouts, headers, and HTTP methods.
|
|
638
413
|
enum SseConnectionHandler {
|
|
639
|
-
|
|
640
|
-
///
|
|
641
|
-
static func
|
|
414
|
+
|
|
415
|
+
/// Constructs a standardized and sanitized URLRequest for SSE streaming.
|
|
416
|
+
static func createRequest(
|
|
642
417
|
url: URL,
|
|
643
418
|
config: SseConfig,
|
|
644
|
-
lastProcessedId: String
|
|
645
|
-
|
|
646
|
-
attemptVersion: Int,
|
|
647
|
-
dispatcher: SseDispatcher,
|
|
648
|
-
protocolClasses: [AnyClass]? = nil
|
|
649
|
-
) -> SseEventSource {
|
|
650
|
-
let sessionConfig = URLSessionConfiguration.default
|
|
651
|
-
let rawReadTimeout = (config.readTimeoutMs ?? 300000.0) / 1000.0
|
|
652
|
-
// Use timeoutIntervalForRequest (resets on incoming chunks) rather than timeoutIntervalForResource.
|
|
653
|
-
// Setting timeoutIntervalForResource would hard-cap the total lifetime of persistent SSE streams.
|
|
654
|
-
// A non-positive timeout interval is treated as infinite fallback sentinel (7 days) to prevent immediate timeout.
|
|
655
|
-
let readTimeout = rawReadTimeout > 0 ? rawReadTimeout : 604800.0
|
|
656
|
-
sessionConfig.timeoutIntervalForRequest = readTimeout
|
|
657
|
-
|
|
658
|
-
if let protocolClasses = protocolClasses {
|
|
659
|
-
sessionConfig.protocolClasses = protocolClasses
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
let rawConnectionTimeout = (config.connectionTimeoutMs ?? 15000.0) / 1000.0
|
|
663
|
-
let connectionTimeout = rawConnectionTimeout > 0 ? rawConnectionTimeout : 0.0
|
|
664
|
-
|
|
419
|
+
lastProcessedId: String?
|
|
420
|
+
) -> URLRequest {
|
|
665
421
|
var request = URLRequest(url: url)
|
|
666
422
|
request.httpMethod = config.method?.stringValue.uppercased() ?? "GET"
|
|
667
|
-
|
|
668
|
-
// Prevent initial
|
|
423
|
+
|
|
424
|
+
// Prevent initial headers from overriding dynamic Last-Event-ID or disabling transparent gzip decompression.
|
|
669
425
|
var headers = config.headers ?? [:]
|
|
670
426
|
headers = headers.filter {
|
|
671
427
|
$0.key.caseInsensitiveCompare("Last-Event-Id") != .orderedSame &&
|
|
672
428
|
$0.key.caseInsensitiveCompare("Accept-Encoding") != .orderedSame
|
|
673
429
|
}
|
|
674
|
-
|
|
430
|
+
|
|
675
431
|
for (key, value) in headers {
|
|
676
432
|
request.setValue(value, forHTTPHeaderField: key)
|
|
677
433
|
}
|
|
678
|
-
|
|
434
|
+
|
|
679
435
|
if let lastId = lastProcessedId, !lastId.isEmpty {
|
|
680
436
|
request.setValue(lastId, forHTTPHeaderField: "Last-Event-ID")
|
|
681
437
|
}
|
|
682
|
-
|
|
438
|
+
|
|
683
439
|
if request.value(forHTTPHeaderField: "Accept") == nil {
|
|
684
440
|
request.setValue("text/event-stream", forHTTPHeaderField: "Accept")
|
|
685
441
|
}
|
|
686
442
|
if request.value(forHTTPHeaderField: "Cache-Control") == nil {
|
|
687
443
|
request.setValue("no-cache", forHTTPHeaderField: "Cache-Control")
|
|
688
444
|
}
|
|
689
|
-
|
|
445
|
+
|
|
690
446
|
if let body = config.body {
|
|
691
447
|
request.httpBody = body.data(using: .utf8)
|
|
692
448
|
}
|
|
693
|
-
|
|
694
|
-
|
|
449
|
+
return request
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// swiftlint:disable function_parameter_count
|
|
453
|
+
/// Instantiates and starts a native `SseEventSource` connection using `SseConfig` and session parameters.
|
|
454
|
+
static func createEventSource(
|
|
455
|
+
url: URL,
|
|
456
|
+
config: SseConfig,
|
|
457
|
+
lastProcessedId: String?,
|
|
458
|
+
delegate: SseConnectionDelegate,
|
|
459
|
+
attemptVersion: Int,
|
|
460
|
+
dispatcher: SseDispatcher,
|
|
461
|
+
protocolClasses: [AnyClass]? = nil
|
|
462
|
+
) -> SseEventSource {
|
|
463
|
+
// swiftlint:enable function_parameter_count
|
|
464
|
+
let sessionConfig = URLSessionConfiguration.default
|
|
465
|
+
let rawReadTimeout = (config.readTimeoutMs ?? 300000.0) / 1000.0
|
|
466
|
+
// Use timeoutIntervalForRequest (resets on incoming chunks) rather than timeoutIntervalForResource.
|
|
467
|
+
// Setting timeoutIntervalForResource would hard-cap the total lifetime of persistent SSE streams.
|
|
468
|
+
// A non-positive timeout interval is treated as infinite fallback (7 days) to prevent immediate timeout.
|
|
469
|
+
let readTimeout = rawReadTimeout > 0 ? rawReadTimeout : 604800.0
|
|
470
|
+
sessionConfig.timeoutIntervalForRequest = readTimeout
|
|
471
|
+
|
|
472
|
+
if let protocolClasses = protocolClasses {
|
|
473
|
+
sessionConfig.protocolClasses = protocolClasses
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
let rawConnectionTimeout = (config.connectionTimeoutMs ?? 15000.0) / 1000.0
|
|
477
|
+
let connectionTimeout = rawConnectionTimeout > 0 ? rawConnectionTimeout : 0.0
|
|
478
|
+
|
|
479
|
+
let request = createRequest(url: url, config: config, lastProcessedId: lastProcessedId)
|
|
480
|
+
|
|
481
|
+
let source = RealSseEventSource(
|
|
482
|
+
delegate: delegate,
|
|
483
|
+
attemptVersion: attemptVersion,
|
|
484
|
+
dispatcher: dispatcher,
|
|
485
|
+
initialLastEventId: lastProcessedId
|
|
486
|
+
)
|
|
695
487
|
source.start(request: request, sessionConfig: sessionConfig, connectionTimeout: connectionTimeout)
|
|
696
488
|
return source
|
|
697
489
|
}
|