react-native-nitro-sse 3.0.0-beta.2 → 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 (50) hide show
  1. package/NitroSse.podspec +0 -1
  2. package/README.md +44 -24
  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 +464 -130
  6. package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +420 -88
  7. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +23 -0
  8. package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +29 -2
  9. package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +9 -0
  10. package/ios/NitroSse.swift +353 -64
  11. package/ios/SseConfig+CopyWith.swift +35 -19
  12. package/ios/SseConnectionHandler.swift +647 -97
  13. package/ios/SseEventBuffer.swift +19 -1
  14. package/ios/SseReconnectStrategy.swift +26 -7
  15. package/lib/module/MockSseEngine.js +72 -8
  16. package/lib/module/NitroSseClient.js +79 -8
  17. package/lib/module/createNitroSse.js +24 -0
  18. package/lib/module/index.js +1 -22
  19. package/lib/module/useNitroSse.js +22 -5
  20. package/lib/typescript/src/MockSseEngine.d.ts +16 -0
  21. package/lib/typescript/src/NitroSse.nitro.d.ts +2 -2
  22. package/lib/typescript/src/NitroSseClient.d.ts +7 -3
  23. package/lib/typescript/src/SseInterface.d.ts +60 -10
  24. package/lib/typescript/src/createNitroSse.d.ts +9 -0
  25. package/lib/typescript/src/index.d.ts +1 -8
  26. package/lib/typescript/src/useNitroSse.d.ts +2 -2
  27. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +12 -8
  28. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.hpp +1 -1
  29. package/nitrogen/generated/android/c++/JSseConfig.hpp +1 -18
  30. package/nitrogen/generated/android/c++/JSseDisconnectReason.hpp +67 -0
  31. package/nitrogen/generated/android/c++/JSseStats.hpp +87 -1
  32. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HybridNitroSseSpec.kt +4 -3
  33. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +4 -13
  34. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseDisconnectReason.kt +26 -0
  35. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseStats.kt +108 -3
  36. package/nitrogen/generated/android/nitrosseOnLoad.cpp +2 -2
  37. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.cpp +8 -8
  38. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +114 -96
  39. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +3 -0
  40. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +7 -4
  41. package/nitrogen/generated/ios/swift/HybridNitroSseSpec.swift +1 -1
  42. package/nitrogen/generated/ios/swift/HybridNitroSseSpec_cxx.swift +34 -1
  43. package/nitrogen/generated/ios/swift/SseConfig.swift +1 -48
  44. package/nitrogen/generated/ios/swift/SseDisconnectReason.swift +52 -0
  45. package/nitrogen/generated/ios/swift/SseStats.swift +217 -2
  46. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.hpp +3 -1
  47. package/nitrogen/generated/shared/c++/SseConfig.hpp +2 -8
  48. package/nitrogen/generated/shared/c++/SseDisconnectReason.hpp +88 -0
  49. package/nitrogen/generated/shared/c++/SseStats.hpp +88 -2
  50. package/package.json +2 -2
@@ -1,18 +1,51 @@
1
1
  package com.margelo.nitro.nitrosse
2
2
 
3
+ import okhttp3.Call
4
+ import okhttp3.Callback
3
5
  import okhttp3.Interceptor
4
6
  import okhttp3.OkHttpClient
5
7
  import okhttp3.Request
6
8
  import okhttp3.Response
7
9
  import okhttp3.ResponseBody
8
- import okhttp3.sse.EventSource
9
- import okhttp3.sse.EventSourceListener
10
- import okhttp3.sse.EventSources
11
- import okio.Buffer
10
+ import okhttp3.ResponseBody.Companion.toResponseBody
11
+ import okio.BufferedSource
12
+ import okio.ByteString
12
13
  import okio.ForwardingSource
13
- import okio.GzipSource
14
14
  import okio.buffer
15
- import java.util.concurrent.atomic.AtomicLong
15
+ import java.io.IOException
16
+
17
+ /**
18
+ * Maximum bytes to read from HTTP error responses to prevent Out-Of-Memory errors.
19
+ */
20
+ const val MAX_ERROR_BODY_BYTES = 8192L
21
+
22
+ /**
23
+ * Maximum bytes allowed for a single SSE line to prevent Out-Of-Memory errors.
24
+ */
25
+ const val MAX_SSE_LINE_LENGTH = 16 * 1024 * 1024L
26
+
27
+ /**
28
+ * Maximum characters allowed for accumulated event data to prevent Out-Of-Memory errors.
29
+ */
30
+ const val MAX_SSE_EVENT_DATA_SIZE = 16 * 1024 * 1024
31
+
32
+ /**
33
+ * CRLF delimiter byte sequence (\r, \n) used for optimized line break scanning.
34
+ */
35
+ private val CRLF_DELIMITERS = ByteString.of('\r'.code.toByte(), '\n'.code.toByte())
36
+
37
+ /**
38
+ * Exception indicating the HTTP response did not have 'text/event-stream' Content-Type per WHATWG SSE specification.
39
+ */
40
+ class InvalidContentTypeException(message: String) : IOException(message)
41
+
42
+ /**
43
+ * Interface representing an active SSE stream connection that can be cancelled.
44
+ */
45
+ interface SseEventSource {
46
+ fun cancel()
47
+ fun request(): Request
48
+ }
16
49
 
17
50
  /**
18
51
  * Interface for delegating OkHttp SSE event callbacks to the connection manager.
@@ -20,120 +53,419 @@ import java.util.concurrent.atomic.AtomicLong
20
53
  interface SseConnectionDelegate {
21
54
  fun connectionDidOpen(response: Response, requestId: String)
22
55
  fun connectionDidReceiveMessage(id: String?, type: String?, data: String, requestId: String)
23
- fun connectionDidFail(t: Throwable?, response: Response?, requestId: String)
56
+ fun connectionDidReceiveComment(comment: String, requestId: String) {}
57
+ fun connectionDidReceiveRetry(retryMs: Long, requestId: String) {}
58
+ fun connectionDidUpdateLastEventId(id: String?, requestId: String) {}
59
+ fun connectionDidReceiveDataChunk(decompressedBytes: Long, requestId: String) {}
60
+ fun connectionDidParseLines(count: Int, requestId: String) {}
61
+ fun connectionDidEncounterParseError(requestId: String) {}
62
+ fun connectionDidFail(t: Throwable?, response: Response?, errorBody: String?, requestId: String) {
63
+ connectionDidFail(t, response, requestId)
64
+ }
65
+ fun connectionDidFail(t: Throwable?, response: Response?, requestId: String) {}
24
66
  fun connectionDidClose(requestId: String)
25
67
  }
26
68
 
27
69
  /**
28
- * Creates OkHttp [EventSource] instances and translates OkHttp callbacks into [SseConnectionDelegate] calls.
70
+ * Sequential line-by-line SSE parser complying with WHATWG Server-Sent Events specification.
71
+ * Ensures strict chronological ordering between data messages, comments, and directives.
29
72
  */
30
- class SseConnectionHandler(private val delegate: SseConnectionDelegate) {
31
-
32
- fun createEventSource(client: OkHttpClient, request: Request, requestId: String): EventSource {
33
- val listener = object : EventSourceListener() {
34
- override fun onOpen(eventSource: EventSource, response: Response) {
35
- delegate.connectionDidOpen(response, requestId)
73
+ internal class SseEventReader(private val source: BufferedSource) {
74
+ interface Callback {
75
+ fun onEvent(id: String?, type: String?, data: String)
76
+ fun onComment(comment: String)
77
+ fun onRetryChange(retryMs: Long)
78
+ fun onIdUpdate(id: String?) {}
79
+ fun onLinesParsed(count: Int) {}
80
+ }
81
+
82
+ private val dataBuffer = StringBuilder()
83
+ private var hasData = false
84
+ private var eventType: String? = null
85
+ private var lastEventId: String? = null
86
+ private var isAtStreamStart = true
87
+ private var skipLeadingLf = false
88
+
89
+ /**
90
+ * Reads a line from [source] handling CRLF (\r\n), bare CR (\r), and LF (\n).
91
+ * Strips leading UTF-8 BOM (0xEF, 0xBB, 0xBF) if present at stream start per WHATWG SSE spec.
92
+ * Operates on [BufferedSource.buffer] using hardware-accelerated [Buffer.indexOfElement] to locate
93
+ * line endings without byte-by-byte Kotlin loop overhead while properly supporting bare carriage returns.
94
+ */
95
+ private fun readSseLine(): String? {
96
+ val buffer = source.buffer
97
+ if (source.exhausted()) return null
98
+
99
+ if (isAtStreamStart) {
100
+ if (source.request(3)) {
101
+ if (buffer.size >= 3 &&
102
+ buffer[0] == 0xEF.toByte() &&
103
+ buffer[1] == 0xBB.toByte() &&
104
+ buffer[2] == 0xBF.toByte()
105
+ ) {
106
+ buffer.skip(3)
107
+ }
108
+ }
109
+ isAtStreamStart = false
110
+ }
111
+
112
+ if (skipLeadingLf) {
113
+ skipLeadingLf = false
114
+ if (buffer.size > 0 && buffer[0] == '\n'.code.toByte()) {
115
+ buffer.skip(1)
116
+ }
117
+ }
118
+
119
+ var scanned = 0L
120
+ while (true) {
121
+ val newlineIndex = buffer.indexOfElement(CRLF_DELIMITERS, scanned)
122
+ if (newlineIndex != -1L) {
123
+ if (newlineIndex > MAX_SSE_LINE_LENGTH) {
124
+ throw IOException("SSE line exceeded maximum limit of $MAX_SSE_LINE_LENGTH bytes")
125
+ }
126
+ val b = buffer[newlineIndex]
127
+ val line = buffer.readUtf8(newlineIndex)
128
+ buffer.skip(1)
129
+ if (b == '\r'.code.toByte()) {
130
+ // If followed immediately by \n in current buffer, consume \n as CRLF.
131
+ // If buffer is exhausted at this exact boundary, defer check via skipLeadingLf
132
+ // to avoid blocking on source.request(1) when server sent bare CR.
133
+ if (buffer.size > 0) {
134
+ if (buffer[0] == '\n'.code.toByte()) {
135
+ buffer.skip(1)
136
+ }
137
+ } else {
138
+ skipLeadingLf = true
139
+ }
140
+ }
141
+ return line
142
+ }
143
+
144
+ if (buffer.size > MAX_SSE_LINE_LENGTH) {
145
+ throw IOException("SSE line exceeded maximum limit of $MAX_SSE_LINE_LENGTH bytes")
146
+ }
147
+
148
+ scanned = buffer.size
149
+ if (!source.request(buffer.size + 1)) {
150
+ if (buffer.size > MAX_SSE_LINE_LENGTH) {
151
+ throw IOException("SSE line exceeded maximum limit of $MAX_SSE_LINE_LENGTH bytes")
152
+ }
153
+ return if (buffer.size > 0) buffer.readUtf8() else null
154
+ }
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Reads lines from source until one event (message or comment) is completed and dispatched.
160
+ * Returns true if an event was dispatched, or false on EOF.
161
+ * Per WHATWG SSE spec: "Once the end of the file is reached, any pending data must be dispatched as an event."
162
+ */
163
+ fun processNextEvent(callback: Callback): Boolean {
164
+ var linesParsedInEvent = 0
165
+ while (true) {
166
+ val line = readSseLine()
167
+ if (line == null) {
168
+ if (linesParsedInEvent > 0) {
169
+ callback.onLinesParsed(linesParsedInEvent)
170
+ }
171
+ if (hasData) {
172
+ val data = dataBuffer.toString()
173
+ val id = lastEventId
174
+ val type = eventType
175
+ dataBuffer.setLength(0)
176
+ hasData = false
177
+ eventType = null
178
+ callback.onEvent(id, type, data)
179
+ return true
180
+ }
181
+ return false
182
+ }
183
+ linesParsedInEvent++
184
+ if (line.isEmpty()) {
185
+ if (hasData) {
186
+ callback.onLinesParsed(linesParsedInEvent)
187
+ val data = dataBuffer.toString()
188
+ val id = lastEventId
189
+ val type = eventType
190
+ dataBuffer.setLength(0)
191
+ hasData = false
192
+ eventType = null
193
+ callback.onEvent(id, type, data)
194
+ return true
195
+ }
196
+ // Delimiter / keepalive empty line without data
197
+ } else if (line.startsWith(":")) {
198
+ callback.onLinesParsed(linesParsedInEvent)
199
+ val rawComment = line.substring(1)
200
+ val commentText = if (rawComment.startsWith(" ")) rawComment.substring(1) else rawComment
201
+ callback.onComment(commentText)
202
+ return true
203
+ } else {
204
+ val colonIndex = line.indexOf(':')
205
+ val field: String
206
+ val value: String
207
+ if (colonIndex != -1) {
208
+ field = line.substring(0, colonIndex)
209
+ val rawValue = line.substring(colonIndex + 1)
210
+ value = if (rawValue.startsWith(" ")) rawValue.substring(1) else rawValue
211
+ } else {
212
+ field = line
213
+ value = ""
214
+ }
215
+ when (field) {
216
+ "data" -> {
217
+ if (dataBuffer.length + value.length > MAX_SSE_EVENT_DATA_SIZE) {
218
+ throw IOException("SSE event data exceeded maximum limit of $MAX_SSE_EVENT_DATA_SIZE characters")
219
+ }
220
+ if (hasData) {
221
+ dataBuffer.append("\n")
222
+ }
223
+ dataBuffer.append(value)
224
+ hasData = true
225
+ }
226
+ "id" -> {
227
+ if (!value.contains('\u0000')) {
228
+ lastEventId = if (value.isEmpty()) null else value
229
+ callback.onIdUpdate(lastEventId)
230
+ }
231
+ }
232
+ "event" -> {
233
+ eventType = if (value.isEmpty()) null else value
234
+ }
235
+ "retry" -> {
236
+ // WHATWG SSE: If field value consists solely of ASCII digits 0-9, set reconnection time. Otherwise ignore.
237
+ if (value.isNotEmpty() && value.all { it in '0'..'9' }) {
238
+ val retryMs = value.toLongOrNull()
239
+ if (retryMs != null && retryMs >= 0) {
240
+ callback.onRetryChange(retryMs)
241
+ }
242
+ }
243
+ }
244
+ }
245
+ }
246
+ }
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Thread-safe EventSource implementation backed by OkHttp [Call] and sequential [SseEventReader].
252
+ */
253
+ internal class RealSseEventSource(
254
+ private val client: OkHttpClient,
255
+ private val request: Request,
256
+ private val delegate: SseConnectionDelegate,
257
+ private val requestId: String
258
+ ) : SseEventSource, Callback {
259
+ private var call: Call? = null
260
+ @Volatile
261
+ private var isCancelled = false
262
+
263
+ fun connect() {
264
+ val newCall = client.newCall(request)
265
+ synchronized(this) {
266
+ if (isCancelled) {
267
+ newCall.cancel()
268
+ return
269
+ }
270
+ call = newCall
271
+ }
272
+ newCall.enqueue(this)
273
+ }
274
+
275
+ override fun request(): Request = request
276
+
277
+ override fun cancel() {
278
+ synchronized(this) {
279
+ isCancelled = true
280
+ call?.cancel()
281
+ }
282
+ }
283
+
284
+ override fun onFailure(call: Call, e: IOException) {
285
+ if (!isCancelled) {
286
+ delegate.connectionDidFail(e, null, null, requestId)
287
+ }
288
+ }
289
+
290
+ override fun onResponse(call: Call, response: Response) {
291
+ if (isCancelled) {
292
+ response.close()
293
+ return
294
+ }
295
+
296
+ // WHATWG SSE Section 9.1: Only HTTP 200 OK responses with text/event-stream establish an SSE stream.
297
+ // Any other HTTP response code (including 201, 204, 206, 4xx, 5xx) must fail the connection.
298
+ if (response.code != 200) {
299
+ val errorBody = if (response.code != 204) {
300
+ try {
301
+ response.peekBody(MAX_ERROR_BODY_BYTES).string()
302
+ } catch (e: Exception) {
303
+ null
304
+ }
305
+ } else null
306
+ delegate.connectionDidFail(null, response, errorBody, requestId)
307
+ response.close()
308
+ return
309
+ }
310
+
311
+
312
+
313
+ // WHATWG SSE: permanently fail and stop without reconnecting on non-event-stream Content-Type.
314
+ val body = response.body
315
+ if (body == null || !isEventStream(body)) {
316
+ val receivedType = body?.contentType()?.toString() ?: "none"
317
+ val error = InvalidContentTypeException("Invalid Content-Type: expected text/event-stream but received '$receivedType'")
318
+ delegate.connectionDidFail(error, response, null, requestId)
319
+ response.close()
320
+ return
321
+ }
322
+
323
+ val emptyResponse = response.newBuilder().body("".toResponseBody(null)).build()
324
+ delegate.connectionDidOpen(emptyResponse, requestId)
325
+
326
+ try {
327
+ val decompressedSource = object : ForwardingSource(body.source()) {
328
+ override fun read(sink: okio.Buffer, byteCount: Long): Long {
329
+ val read = super.read(sink, byteCount)
330
+ if (read > 0 && !isCancelled) {
331
+ this@RealSseEventSource.delegate.connectionDidReceiveDataChunk(read, requestId)
332
+ }
333
+ return read
334
+ }
36
335
  }
336
+ val reader = SseEventReader(decompressedSource.buffer())
337
+ val callback = object : SseEventReader.Callback {
338
+ override fun onEvent(id: String?, type: String?, data: String) {
339
+ if (!isCancelled) {
340
+ delegate.connectionDidReceiveMessage(id, type, data, requestId)
341
+ }
342
+ }
37
343
 
38
- override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) {
39
- delegate.connectionDidReceiveMessage(id, type, data, requestId)
344
+ override fun onComment(comment: String) {
345
+ if (!isCancelled) {
346
+ delegate.connectionDidReceiveComment(comment, requestId)
347
+ }
348
+ }
349
+
350
+ override fun onRetryChange(retryMs: Long) {
351
+ if (!isCancelled) {
352
+ delegate.connectionDidReceiveRetry(retryMs, requestId)
353
+ }
354
+ }
355
+
356
+ override fun onIdUpdate(id: String?) {
357
+ if (!isCancelled) {
358
+ delegate.connectionDidUpdateLastEventId(id, requestId)
359
+ }
360
+ }
361
+
362
+ override fun onLinesParsed(count: Int) {
363
+ if (!isCancelled) {
364
+ delegate.connectionDidParseLines(count, requestId)
365
+ }
366
+ }
40
367
  }
41
368
 
42
- override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
43
- delegate.connectionDidFail(t, response, requestId)
369
+ while (!isCancelled && reader.processNextEvent(callback)) {
370
+ // Read and dispatch events sequentially
44
371
  }
45
372
 
46
- override fun onClosed(eventSource: EventSource) {
373
+ if (!isCancelled) {
47
374
  delegate.connectionDidClose(requestId)
48
375
  }
376
+ } catch (e: Exception) {
377
+ if (!isCancelled) {
378
+ if (e is InvalidContentTypeException ||
379
+ e.message?.contains("SSE line exceeded") == true ||
380
+ e.message?.contains("SSE event data exceeded") == true
381
+ ) {
382
+ delegate.connectionDidEncounterParseError(requestId)
383
+ }
384
+ delegate.connectionDidFail(e, null, null, requestId)
385
+ }
386
+ } finally {
387
+ response.close()
49
388
  }
50
- return EventSources.createFactory(client).newEventSource(request, listener)
389
+ }
390
+
391
+ private fun isEventStream(body: ResponseBody): Boolean {
392
+ val contentType = body.contentType() ?: return false
393
+ return contentType.type == "text" && contentType.subtype == "event-stream"
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Creates OkHttp [EventSource] instances and translates callbacks into [SseConnectionDelegate] calls.
399
+ */
400
+ class SseConnectionHandler(private val delegate: SseConnectionDelegate) {
401
+
402
+ fun createEventSource(client: OkHttpClient, request: Request, requestId: String): SseEventSource {
403
+ val eventSource = RealSseEventSource(client, request, delegate, requestId)
404
+ eventSource.connect()
405
+ return eventSource
51
406
  }
52
407
  }
53
408
 
54
409
  /**
55
- * Network interceptor for byte accounting and SSE heartbeat/comment detection.
56
- * Sniffs raw stream before EventSourceReader discards SSE comments (`:`).
410
+ * Shared tracker recording raw network socket transport metrics from InspectorNetworkInterceptor.
57
411
  */
58
- internal class HeartbeatNetworkInterceptor(
59
- private val totalBytesReceived: AtomicLong? = null,
60
- private val onHeartbeat: (requestId: String?, comment: String) -> Unit
61
- ) : Interceptor {
62
- constructor(onHeartbeat: (requestId: String?, comment: String) -> Unit) : this(null, onHeartbeat)
412
+ object SseNetworkMetricsTracker {
413
+ private val rawBytesMap = java.util.concurrent.ConcurrentHashMap<String, java.util.concurrent.atomic.AtomicLong>()
414
+ private val gzipMap = java.util.concurrent.ConcurrentHashMap<String, Boolean>()
415
+ private val chunksMap = java.util.concurrent.ConcurrentHashMap<String, java.util.concurrent.atomic.AtomicLong>()
416
+
417
+ fun recordRawBytes(requestId: String, bytes: Long, isGzip: Boolean) {
418
+ rawBytesMap.computeIfAbsent(requestId) { java.util.concurrent.atomic.AtomicLong(0) }.addAndGet(bytes)
419
+ chunksMap.computeIfAbsent(requestId) { java.util.concurrent.atomic.AtomicLong(0) }.incrementAndGet()
420
+ if (isGzip) {
421
+ gzipMap[requestId] = true
422
+ }
423
+ }
424
+
425
+ fun getRawBytes(requestId: String): Long? = rawBytesMap[requestId]?.get()
426
+ fun getChunks(requestId: String): Long? = chunksMap[requestId]?.get()
427
+ fun isGzip(requestId: String): Boolean = gzipMap[requestId] == true
428
+
429
+ fun clear(requestId: String) {
430
+ rawBytesMap.remove(requestId)
431
+ gzipMap.remove(requestId)
432
+ chunksMap.remove(requestId)
433
+ }
434
+ }
63
435
 
436
+ /**
437
+ * Network interceptor for recording raw wire response metadata for React Native DevTools.
438
+ * Runs at the network layer to capture true HTTP status, raw wire headers (e.g. Content-Encoding: gzip), and timing.
439
+ */
440
+ internal class InspectorNetworkInterceptor : Interceptor {
64
441
  override fun intercept(chain: Interceptor.Chain): Response {
65
442
  val request = chain.request()
66
443
  val rid = request.tag(String::class.java)
67
-
68
444
  val response = chain.proceed(request)
69
-
70
445
  rid?.let {
71
446
  NetworkInspector.reportResponseStart(it, request, response)
72
447
  }
73
-
74
448
  val responseBody = response.body
75
- if (responseBody != null) {
76
- val isGzip = "gzip".equals(response.header("Content-Encoding"), ignoreCase = true)
77
- val rawSource = if (isGzip) {
78
- GzipSource(responseBody.source())
79
- } else {
80
- responseBody.source()
81
- }
82
-
83
- val countingBody = object : ResponseBody() {
84
- override fun contentType() = responseBody.contentType()
85
- override fun contentLength() = if (isGzip) -1L else responseBody.contentLength()
86
-
87
- private val bufferedSource by lazy {
88
- (object : ForwardingSource(rawSource) {
89
- private var isAtStartOfLine = true
90
- private var isReadingComment = false
91
- private val commentBuffer = java.io.ByteArrayOutputStream()
92
-
93
- override fun read(sink: Buffer, byteCount: Long): Long {
94
- val scratch = Buffer()
95
- val bytesRead = super.read(scratch, byteCount)
96
- if (bytesRead != -1L) {
97
- totalBytesReceived?.addAndGet(bytesRead)
98
- try {
99
- val bytes = scratch.snapshot().toByteArray()
100
- for (b in bytes) {
101
- val isNewline = (b == '\n'.code.toByte() || b == '\r'.code.toByte())
102
- if (isReadingComment) {
103
- if (isNewline) {
104
- isReadingComment = false
105
- val rawComment = commentBuffer.toString("UTF-8")
106
- // WHATWG SSE Spec: Remove only a single leading space after ':' if present
107
- val commentText = if (rawComment.startsWith(" ")) rawComment.substring(1) else rawComment
108
- commentBuffer.reset()
109
- onHeartbeat(rid, commentText)
110
- } else {
111
- commentBuffer.write(b.toInt())
112
- }
113
- } else if (isAtStartOfLine && b == ':'.code.toByte()) {
114
- isReadingComment = true
115
- commentBuffer.reset()
116
- }
117
- isAtStartOfLine = isNewline
118
- }
119
- } catch (e: Exception) {
120
- // Swallow byte scanning errors to prevent stream reader failure if buffer inspection fails
121
- }
122
- sink.write(scratch, bytesRead)
123
- }
124
- return bytesRead
125
- }
126
- }).buffer()
449
+ if (responseBody != null && rid != null) {
450
+ val isGzip = response.header("Content-Encoding")?.equals("gzip", ignoreCase = true) == true
451
+ val trackingSource = object : ForwardingSource(responseBody.source()) {
452
+ override fun read(sink: okio.Buffer, byteCount: Long): Long {
453
+ val read = super.read(sink, byteCount)
454
+ if (read > 0) {
455
+ SseNetworkMetricsTracker.recordRawBytes(rid, read, isGzip)
456
+ }
457
+ return read
127
458
  }
128
-
129
- override fun source() = bufferedSource
130
459
  }
131
- val responseBuilder = response.newBuilder().body(countingBody)
132
- if (isGzip) {
133
- responseBuilder.removeHeader("Content-Encoding").removeHeader("Content-Length")
460
+ val wrappedBody = object : ResponseBody() {
461
+ override fun contentType() = responseBody.contentType()
462
+ override fun contentLength() = responseBody.contentLength()
463
+ override fun source(): BufferedSource = trackingSource.buffer()
134
464
  }
135
- return responseBuilder.build()
465
+ return response.newBuilder().body(wrappedBody).build()
136
466
  }
137
467
  return response
138
468
  }
139
469
  }
470
+
471
+
@@ -16,12 +16,18 @@ class SseEventBuffer(
16
16
  @Volatile
17
17
  private var onFlush: (Array<SseEvent>) -> Unit = onFlush
18
18
 
19
+ var onFlushError: ((Exception) -> Unit)? = null
20
+
19
21
  private val eventBuffer = mutableListOf<SseEvent>()
20
22
  private val isFlushPending = AtomicBoolean(false)
21
23
 
22
24
  private var batchingIntervalMs: Double = 0.0
23
25
  private var maxBufferSize: Int = 1000
24
26
 
27
+ private var peakBufferedEvents: Int = 0
28
+ private var bufferFlushCount: Long = 0
29
+ private var bufferOverflowCount: Long = 0
30
+
25
31
  private val flushRunnable = Runnable { flush() }
26
32
 
27
33
  fun configure(batchingIntervalMs: Double, maxBufferSize: Int) {
@@ -37,17 +43,28 @@ class SseEventBuffer(
37
43
  this.onFlush = {}
38
44
  }
39
45
 
46
+ fun getEventsBuffered(): Int = synchronized(eventBuffer) { eventBuffer.size }
47
+ fun getPeakBufferedEvents(): Int = synchronized(eventBuffer) { peakBufferedEvents }
48
+ fun getBufferFlushCount(): Long = synchronized(eventBuffer) { bufferFlushCount }
49
+ fun getBufferOverflowCount(): Long = synchronized(eventBuffer) { bufferOverflowCount }
50
+
40
51
  fun push(event: SseEvent) {
41
52
  if (batchingIntervalMs <= 0.0) {
42
53
  if (dispatcher == null || dispatcher.isCurrentDispatcher()) {
43
54
  synchronized(eventBuffer) {
44
55
  eventBuffer.add(event)
56
+ if (eventBuffer.size > peakBufferedEvents) {
57
+ peakBufferedEvents = eventBuffer.size
58
+ }
45
59
  }
46
60
  flush()
47
61
  } else {
48
62
  dispatcher.post {
49
63
  synchronized(eventBuffer) {
50
64
  eventBuffer.add(event)
65
+ if (eventBuffer.size > peakBufferedEvents) {
66
+ peakBufferedEvents = eventBuffer.size
67
+ }
51
68
  }
52
69
  flush()
53
70
  }
@@ -58,7 +75,11 @@ class SseEventBuffer(
58
75
  var shouldFlush = false
59
76
  synchronized(eventBuffer) {
60
77
  eventBuffer.add(event)
78
+ if (eventBuffer.size > peakBufferedEvents) {
79
+ peakBufferedEvents = eventBuffer.size
80
+ }
61
81
  if (eventBuffer.size >= maxBufferSize) {
82
+ bufferOverflowCount++
62
83
  shouldFlush = true
63
84
  }
64
85
  }
@@ -86,6 +107,7 @@ class SseEventBuffer(
86
107
  isFlushPending.set(false)
87
108
  return
88
109
  }
110
+ bufferFlushCount++
89
111
  eventsToEmit = eventBuffer.toTypedArray()
90
112
  eventBuffer.clear()
91
113
  isFlushPending.set(false)
@@ -95,6 +117,7 @@ class SseEventBuffer(
95
117
  onFlush(eventsToEmit)
96
118
  } catch (e: Exception) {
97
119
  Log.e("SseEventBuffer", "Error invoking onFlush: ${e.message}")
120
+ onFlushError?.invoke(e)
98
121
  }
99
122
  }
100
123