react-native-nitro-sse 3.0.0 → 3.1.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.
Files changed (29) hide show
  1. package/NitroSse.podspec +0 -1
  2. package/README.md +1 -1
  3. package/android/build.gradle +0 -1
  4. package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +33 -10
  5. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +366 -78
  6. package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +417 -94
  7. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +20 -0
  8. package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +9 -0
  9. package/ios/NitroSse.swift +302 -49
  10. package/ios/SseConnectionHandler.swift +647 -97
  11. package/ios/SseEventBuffer.swift +19 -1
  12. package/ios/SseReconnectStrategy.swift +26 -7
  13. package/lib/module/MockSseEngine.js +72 -3
  14. package/lib/module/NitroSseClient.js +24 -1
  15. package/lib/typescript/src/MockSseEngine.d.ts +16 -0
  16. package/lib/typescript/src/SseInterface.d.ts +46 -3
  17. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +4 -0
  18. package/nitrogen/generated/android/c++/JSseDisconnectReason.hpp +67 -0
  19. package/nitrogen/generated/android/c++/JSseStats.hpp +87 -1
  20. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseDisconnectReason.kt +26 -0
  21. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseStats.kt +108 -3
  22. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +18 -0
  23. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +3 -0
  24. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +3 -0
  25. package/nitrogen/generated/ios/swift/SseDisconnectReason.swift +52 -0
  26. package/nitrogen/generated/ios/swift/SseStats.swift +217 -2
  27. package/nitrogen/generated/shared/c++/SseDisconnectReason.hpp +88 -0
  28. package/nitrogen/generated/shared/c++/SseStats.hpp +88 -2
  29. package/package.json +2 -2
@@ -1,148 +1,698 @@
1
1
  import Foundation
2
- import LDSwiftEventSource
3
2
 
4
3
  /// Delegate protocol for receiving lifecycle and stream events from `SseConnectionHandler`.
5
4
  protocol SseConnectionDelegate: AnyObject {
6
- func connectionDidOpen(attemptVersion: Int)
5
+ func connectionDidOpen(response: HTTPURLResponse, attemptVersion: Int)
7
6
  func connectionDidClose(attemptVersion: Int)
8
7
  func connectionDidReceiveMessage(eventType: String, data: String, lastEventId: String, attemptVersion: Int)
9
8
  func connectionDidReceiveComment(_ comment: String, attemptVersion: Int)
10
- func connectionDidFail(error: Error, attemptVersion: Int)
9
+ func connectionDidReceiveRetry(retryMs: Int64, attemptVersion: Int)
10
+ func connectionDidFail(error: Error, response: HTTPURLResponse?, errorBody: String?, attemptVersion: Int)
11
+ func connectionDidUpdateLastEventId(id: String?, attemptVersion: Int)
12
+ func connectionDidReceiveDataChunk(chunkLength: Int, rawWireBytes: Int64, decompressedBytes: Int64?, attemptVersion: Int)
13
+ func connectionDidParseLines(count: Int, attemptVersion: Int)
14
+ func connectionDidEncounterParseError(attemptVersion: Int)
11
15
  }
12
16
 
13
- /// Factory constructing `LDSwiftEventSource.EventSource` instances configured with custom timeouts, headers, and HTTP methods.
14
- enum SseConnectionHandler {
17
+ extension SseConnectionDelegate {
18
+ func connectionDidFail(error: Error, attemptVersion: Int) {
19
+ connectionDidFail(error: error, response: nil, errorBody: nil, attemptVersion: attemptVersion)
20
+ }
21
+
22
+ func connectionDidFail(error: Error, response: HTTPURLResponse?, attemptVersion: Int) {
23
+ connectionDidFail(error: error, response: response, errorBody: nil, attemptVersion: attemptVersion)
24
+ }
15
25
 
16
- /// Instantiates and starts an `EventSource` connection using `SseConfig` properties and initial event ID state.
17
- static func createEventSource(
18
- url: URL,
19
- config: SseConfig,
20
- lastProcessedId: String?,
21
- delegate: SseConnectionDelegate,
22
- attemptVersion: Int,
23
- dispatcher: SseDispatcher
24
- ) -> EventSource {
25
- let sessionConfig = URLSessionConfiguration.default
26
- let readTimeout = (config.readTimeoutMs ?? 300000.0) / 1000.0
27
- // Use timeoutIntervalForRequest (resets on incoming chunks) rather than timeoutIntervalForResource.
28
- // Setting timeoutIntervalForResource would hard-cap the total lifetime of persistent SSE streams.
29
- sessionConfig.timeoutIntervalForRequest = readTimeout
26
+ func connectionDidReceiveRetry(retryMs: Int64, attemptVersion: Int) {}
27
+
28
+ func connectionDidUpdateLastEventId(id: String?, attemptVersion: Int) {}
29
+
30
+ func connectionDidReceiveDataChunk(chunkLength: Int, rawWireBytes: Int64, decompressedBytes: Int64?, attemptVersion: Int) {}
31
+
32
+ func connectionDidParseLines(count: Int, attemptVersion: Int) {}
33
+
34
+ func connectionDidEncounterParseError(attemptVersion: Int) {}
35
+ }
36
+
37
+ /// Maximum bytes to read from HTTP error responses to prevent Out-Of-Memory errors.
38
+ private let MAX_ERROR_BODY_BYTES: Int = 8192
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
45
+
46
+ /// Protocol representing an active SSE connection that can be cancelled.
47
+ protocol SseEventSource: AnyObject {
48
+ func stop()
49
+ }
50
+
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
+ }
30
126
 
31
- let connectionTimeout = (config.connectionTimeoutMs ?? 15000.0) / 1000.0
32
- let handler = SseHandler(delegate: delegate, attemptVersion: attemptVersion, dispatcher: dispatcher)
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.
37
- esConfig.connectionErrorHandler = { [weak handler] error in
38
- handler?.onError(error: error)
39
- return .shutdown
40
- }
41
- esConfig.urlSessionConfiguration = sessionConfig
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 ?? ""
47
- if let lastId = lastProcessedId, !lastId.isEmpty {
48
- esConfig.headerTransform = { headers in
49
- var transformed = headers
50
- transformed["Last-Event-Id"] = lastId
51
- return transformed
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)
52
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
53
293
  }
54
- esConfig.method = config.method?.stringValue.uppercased() ?? "GET"
55
- esConfig.body = config.body?.data(using: .utf8)
56
294
 
57
- let es = EventSource(config: esConfig)
58
- handler.source = es
59
- handler.startConnectionTimer(timeout: connectionTimeout)
60
- es.start()
61
- return es
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
+ }
62
341
  }
63
342
  }
64
343
 
65
- // MARK: - SseHandler
344
+ // MARK: - RealSseEventSource
66
345
 
67
- /// Adapts `LDSwiftEventSource.EventHandler` callbacks into `SseConnectionDelegate` dispatches.
68
- /// Ensures all events are safely posted to the specified `SseDispatcher` queue and checks source identity to filter stale events.
69
- private class SseHandler: EventHandler {
70
- weak var delegate: SseConnectionDelegate?
71
- weak var source: EventSource?
72
- let attemptVersion: Int
73
- let dispatcher: SseDispatcher
74
- private var isConnectedOrFinished: Bool = false
346
+ /// Native EventSource implementation backed by Apple Foundation `URLSession` and `URLSessionDataDelegate`.
347
+ internal class RealSseEventSource: NSObject, URLSessionDataDelegate, SseEventSource, SseEventParserDelegate {
348
+ private weak var delegate: SseConnectionDelegate?
349
+ private let attemptVersion: Int
350
+ private let dispatcher: SseDispatcher
351
+
352
+ private var session: URLSession?
353
+ private var task: URLSessionDataTask?
354
+ private let parser: SseEventParser
355
+
356
+ private var didReceiveValidResponse: Bool = false
357
+ private var isFinished: Bool = false
75
358
  private var isTerminalDispatched: Bool = false
359
+ private var isCancelled: Bool = false
360
+ private var lastResponse: HTTPURLResponse?
361
+ private var isGzip: Bool = false
362
+ private var decompressedBytesReceived: Int64 = 0
363
+ private var isCollectingErrorBody: Bool = false
364
+ private var errorBodyData = Data()
365
+ private var pendingErrorResponse: HTTPURLResponse?
76
366
 
77
- init(delegate: SseConnectionDelegate, attemptVersion: Int, dispatcher: SseDispatcher) {
367
+ init(delegate: SseConnectionDelegate, attemptVersion: Int, dispatcher: SseDispatcher, initialLastEventId: String? = nil) {
78
368
  self.delegate = delegate
79
369
  self.attemptVersion = attemptVersion
80
370
  self.dispatcher = dispatcher
371
+ self.parser = SseEventParser(initialLastEventId: initialLastEventId)
372
+ super.init()
373
+ self.parser.delegate = self
374
+ }
375
+
376
+ func start(
377
+ request: URLRequest,
378
+ sessionConfig: URLSessionConfiguration,
379
+ connectionTimeout: TimeInterval
380
+ ) {
381
+ let queue = OperationQueue()
382
+ queue.maxConcurrentOperationCount = 1
383
+ queue.name = "com.margelo.nitro.sse.urlsession"
384
+
385
+ let session = URLSession(configuration: sessionConfig, delegate: self, delegateQueue: queue)
386
+ self.session = session
387
+
388
+ let task = session.dataTask(with: request)
389
+ self.task = task
390
+
391
+ if connectionTimeout > 0 {
392
+ startConnectionTimer(timeout: connectionTimeout)
393
+ }
394
+ task.resume()
81
395
  }
82
396
 
83
- private func dispatchToDelegate(isTerminal: Bool = false, _ action: @escaping (SseConnectionDelegate) -> Void) {
397
+ func stop() {
84
398
  dispatcher.async { [weak self] in
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)
399
+ guard let self = self, !self.isCancelled else { return }
400
+ self.isCancelled = true
401
+ self.isFinished = true
402
+ self.cleanupTransport()
93
403
  }
94
404
  }
95
405
 
96
- func startConnectionTimer(timeout: TimeInterval) {
406
+ private func cleanupTransport() {
407
+ dispatcher.assertOnQueue()
408
+ task?.cancel()
409
+ session?.invalidateAndCancel()
410
+ task = nil
411
+ session = nil
412
+ }
413
+
414
+ private func startConnectionTimer(timeout: TimeInterval) {
97
415
  guard timeout > 0 else { return }
98
416
  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
417
+ guard let self = self, !self.didReceiveValidResponse, !self.isFinished, !self.isCancelled else { return }
418
+ self.isFinished = true
419
+ let error = NSError(
420
+ domain: NSURLErrorDomain,
421
+ code: NSURLErrorTimedOut,
422
+ userInfo: [NSLocalizedDescriptionKey: "Connection timed out after \(timeout) seconds"]
107
423
  )
424
+ self.dispatchTerminalFailure(error: error, response: nil, errorBody: nil)
108
425
  }
109
426
  }
110
427
 
111
- func onOpened() {
112
- dispatchToDelegate { delegate in
113
- delegate.connectionDidOpen(attemptVersion: self.attemptVersion)
114
- }
428
+ // MARK: - URLSessionTaskDelegate & URLSessionDataDelegate
429
+
430
+ func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
431
+ // Delegate callback confirming invalidation of the session and its delegate retain cycle.
115
432
  }
116
433
 
117
- func onClosed() {
118
- dispatchToDelegate(isTerminal: true) { delegate in
119
- delegate.connectionDidClose(attemptVersion: self.attemptVersion)
434
+ func urlSession(
435
+ _ session: URLSession,
436
+ dataTask: URLSessionDataTask,
437
+ didReceive response: URLResponse,
438
+ completionHandler: @escaping (URLSession.ResponseDisposition) -> Void
439
+ ) {
440
+ dispatcher.async { [weak self] in
441
+ guard let self = self, !self.isCancelled else {
442
+ completionHandler(.cancel)
443
+ return
444
+ }
445
+
446
+ 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
+ let error = NSError(
460
+ domain: "NitroSse",
461
+ code: 204,
462
+ userInfo: [NSLocalizedDescriptionKey: "HTTP 204 No Content"]
463
+ )
464
+ self.isFinished = true
465
+ self.dispatchTerminalFailure(error: error, response: httpResponse, errorBody: nil)
466
+ completionHandler(.cancel)
467
+ return
468
+ }
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
+
480
+ self.isCollectingErrorBody = true
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)
120
512
  }
121
513
  }
122
514
 
123
- func onMessage(eventType: String, messageEvent: MessageEvent) {
124
- dispatchToDelegate { delegate in
125
- delegate.connectionDidReceiveMessage(
126
- eventType: eventType,
127
- data: messageEvent.data,
128
- lastEventId: messageEvent.lastEventId,
515
+ func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
516
+ dispatcher.async { [weak self] in
517
+ guard let self = self, !self.isCancelled, !self.isTerminalDispatched else { return }
518
+ if self.isCollectingErrorBody {
519
+ let remaining = MAX_ERROR_BODY_BYTES - self.errorBodyData.count
520
+ if remaining > 0 {
521
+ let chunk = data.count > remaining ? data.prefix(remaining) : data
522
+ self.errorBodyData.append(chunk)
523
+ }
524
+ if self.errorBodyData.count >= MAX_ERROR_BODY_BYTES {
525
+ self.isCollectingErrorBody = false
526
+ let resp = self.pendingErrorResponse ?? self.lastResponse
527
+ let statusCode = resp?.statusCode ?? 500
528
+ let error = NSError(domain: "NitroSse", code: statusCode, userInfo: [NSLocalizedDescriptionKey: "HTTP \(statusCode)"])
529
+ let bodyString = String(decoding: self.errorBodyData, as: UTF8.self)
530
+ self.dispatchTerminalFailure(error: error, response: resp, errorBody: bodyString)
531
+ }
532
+ return
533
+ }
534
+ self.decompressedBytesReceived += Int64(data.count)
535
+ let rawBytesCount = dataTask.countOfBytesReceived > 0 ? dataTask.countOfBytesReceived : self.decompressedBytesReceived
536
+ if !self.isGzip && dataTask.countOfBytesReceived > 0 && self.decompressedBytesReceived > dataTask.countOfBytesReceived {
537
+ self.isGzip = true
538
+ }
539
+ self.delegate?.connectionDidReceiveDataChunk(
540
+ chunkLength: data.count,
541
+ rawWireBytes: rawBytesCount,
542
+ decompressedBytes: self.isGzip ? self.decompressedBytesReceived : nil,
129
543
  attemptVersion: self.attemptVersion
130
544
  )
545
+ self.parser.feed(data: data)
131
546
  }
132
547
  }
133
548
 
134
- /// Maps native SSE comments (lines starting with ':') to heartbeat events.
135
- /// Normalizes comment by removing single leading space per WHATWG SSE specification for cross-platform parity.
136
- func onComment(comment: String) {
137
- let normalized = comment.hasPrefix(" ") ? String(comment.dropFirst()) : comment
138
- dispatchToDelegate { delegate in
139
- delegate.connectionDidReceiveComment(normalized, attemptVersion: self.attemptVersion)
549
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
550
+ dispatcher.async { [weak self] in
551
+ guard let self = self, !self.isCancelled else { return }
552
+ self.isFinished = true
553
+
554
+ if self.isCollectingErrorBody {
555
+ self.isCollectingErrorBody = false
556
+ let resp = self.pendingErrorResponse ?? self.lastResponse
557
+ let statusCode = resp?.statusCode ?? 500
558
+ let finalError = error ?? NSError(domain: "NitroSse", code: statusCode, userInfo: [NSLocalizedDescriptionKey: "HTTP \(statusCode)"])
559
+ let bodyString = self.errorBodyData.isEmpty ? nil : String(decoding: self.errorBodyData, as: UTF8.self)
560
+ self.dispatchTerminalFailure(error: finalError, response: resp, errorBody: bodyString)
561
+ return
562
+ }
563
+
564
+ if let error = error {
565
+ let nsError = error as NSError
566
+ if nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorCancelled {
567
+ // Intentionally cancelled or stopped
568
+ self.cleanupTransport()
569
+ return
570
+ }
571
+ self.dispatchTerminalFailure(error: error, response: self.lastResponse, errorBody: nil)
572
+ } else {
573
+ guard !self.isTerminalDispatched else { return }
574
+ self.isTerminalDispatched = true
575
+ self.parser.endOfStream()
576
+ self.cleanupTransport()
577
+ self.delegate?.connectionDidClose(attemptVersion: self.attemptVersion)
578
+ }
140
579
  }
141
580
  }
142
581
 
143
- func onError(error: Error) {
144
- dispatchToDelegate(isTerminal: true) { delegate in
145
- delegate.connectionDidFail(error: error, attemptVersion: self.attemptVersion)
582
+ private func dispatchTerminalFailure(error: Error, response: HTTPURLResponse?, errorBody: String? = nil) {
583
+ guard !isTerminalDispatched else { return }
584
+ isTerminalDispatched = true
585
+ isFinished = true
586
+ cleanupTransport()
587
+ delegate?.connectionDidFail(error: error, response: response, errorBody: errorBody, attemptVersion: attemptVersion)
588
+ }
589
+
590
+ // MARK: - SseEventParserDelegate
591
+
592
+ func parserDidReceiveEvent(id: String?, type: String?, data: String) {
593
+ dispatcher.assertOnQueue()
594
+ guard !isCancelled, !isTerminalDispatched else { return }
595
+ delegate?.connectionDidReceiveMessage(
596
+ eventType: type ?? "message",
597
+ data: data,
598
+ lastEventId: id ?? "",
599
+ attemptVersion: attemptVersion
600
+ )
601
+ }
602
+
603
+ func parserDidReceiveComment(_ comment: String) {
604
+ dispatcher.assertOnQueue()
605
+ guard !isCancelled, !isTerminalDispatched else { return }
606
+ delegate?.connectionDidReceiveComment(comment, attemptVersion: attemptVersion)
607
+ }
608
+
609
+ func parserDidReceiveRetry(retryMs: Int64) {
610
+ dispatcher.assertOnQueue()
611
+ guard !isCancelled, !isTerminalDispatched else { return }
612
+ delegate?.connectionDidReceiveRetry(retryMs: retryMs, attemptVersion: attemptVersion)
613
+ }
614
+
615
+ func parserDidUpdateLastEventId(_ id: String?) {
616
+ dispatcher.assertOnQueue()
617
+ guard !isCancelled, !isTerminalDispatched else { return }
618
+ delegate?.connectionDidUpdateLastEventId(id: id, attemptVersion: attemptVersion)
619
+ }
620
+
621
+ func parserDidParseLines(_ count: Int) {
622
+ dispatcher.assertOnQueue()
623
+ guard !isCancelled, !isTerminalDispatched else { return }
624
+ delegate?.connectionDidParseLines(count: count, attemptVersion: attemptVersion)
625
+ }
626
+
627
+ func parserDidFail(error: Error) {
628
+ dispatcher.assertOnQueue()
629
+ guard !isCancelled, !isTerminalDispatched else { return }
630
+ delegate?.connectionDidEncounterParseError(attemptVersion: attemptVersion)
631
+ dispatchTerminalFailure(error: error, response: lastResponse, errorBody: nil)
632
+ }
633
+ }
634
+
635
+ // MARK: - SseConnectionHandler Factory
636
+
637
+ /// Factory creating native `RealSseEventSource` instances configured with custom timeouts, headers, and HTTP methods.
638
+ enum SseConnectionHandler {
639
+
640
+ /// Instantiates and starts a native `SseEventSource` connection using `SseConfig` and session parameters.
641
+ static func createEventSource(
642
+ url: URL,
643
+ config: SseConfig,
644
+ lastProcessedId: String?,
645
+ delegate: SseConnectionDelegate,
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
+
665
+ var request = URLRequest(url: url)
666
+ request.httpMethod = config.method?.stringValue.uppercased() ?? "GET"
667
+
668
+ // Prevent initial config headers from overriding the dynamic Last-Event-ID or disabling transparent gzip decompression.
669
+ var headers = config.headers ?? [:]
670
+ headers = headers.filter {
671
+ $0.key.caseInsensitiveCompare("Last-Event-Id") != .orderedSame &&
672
+ $0.key.caseInsensitiveCompare("Accept-Encoding") != .orderedSame
673
+ }
674
+
675
+ for (key, value) in headers {
676
+ request.setValue(value, forHTTPHeaderField: key)
146
677
  }
678
+
679
+ if let lastId = lastProcessedId, !lastId.isEmpty {
680
+ request.setValue(lastId, forHTTPHeaderField: "Last-Event-ID")
681
+ }
682
+
683
+ if request.value(forHTTPHeaderField: "Accept") == nil {
684
+ request.setValue("text/event-stream", forHTTPHeaderField: "Accept")
685
+ }
686
+ if request.value(forHTTPHeaderField: "Cache-Control") == nil {
687
+ request.setValue("no-cache", forHTTPHeaderField: "Cache-Control")
688
+ }
689
+
690
+ if let body = config.body {
691
+ request.httpBody = body.data(using: .utf8)
692
+ }
693
+
694
+ let source = RealSseEventSource(delegate: delegate, attemptVersion: attemptVersion, dispatcher: dispatcher, initialLastEventId: lastProcessedId)
695
+ source.start(request: request, sessionConfig: sessionConfig, connectionTimeout: connectionTimeout)
696
+ return source
147
697
  }
148
698
  }