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.
- package/NitroSse.podspec +0 -1
- package/README.md +1 -1
- package/android/build.gradle +0 -1
- package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +33 -10
- package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +366 -78
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +417 -94
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +20 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +9 -0
- package/ios/NitroSse.swift +302 -49
- package/ios/SseConnectionHandler.swift +647 -97
- package/ios/SseEventBuffer.swift +19 -1
- package/ios/SseReconnectStrategy.swift +26 -7
- package/lib/module/MockSseEngine.js +72 -3
- package/lib/module/NitroSseClient.js +24 -1
- package/lib/typescript/src/MockSseEngine.d.ts +16 -0
- package/lib/typescript/src/SseInterface.d.ts +46 -3
- package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +4 -0
- package/nitrogen/generated/android/c++/JSseDisconnectReason.hpp +67 -0
- package/nitrogen/generated/android/c++/JSseStats.hpp +87 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseDisconnectReason.kt +26 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseStats.kt +108 -3
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +18 -0
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +3 -0
- package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +3 -0
- package/nitrogen/generated/ios/swift/SseDisconnectReason.swift +52 -0
- package/nitrogen/generated/ios/swift/SseStats.swift +217 -2
- package/nitrogen/generated/shared/c++/SseDisconnectReason.hpp +88 -0
- package/nitrogen/generated/shared/c++/SseStats.hpp +88 -2
- package/package.json +2 -2
|
@@ -1,17 +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.
|
|
9
|
-
import
|
|
10
|
-
import
|
|
11
|
-
import okio.Buffer
|
|
10
|
+
import okhttp3.ResponseBody.Companion.toResponseBody
|
|
11
|
+
import okio.BufferedSource
|
|
12
|
+
import okio.ByteString
|
|
12
13
|
import okio.ForwardingSource
|
|
13
14
|
import okio.buffer
|
|
14
|
-
import java.
|
|
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
|
+
}
|
|
15
49
|
|
|
16
50
|
/**
|
|
17
51
|
* Interface for delegating OkHttp SSE event callbacks to the connection manager.
|
|
@@ -19,130 +53,419 @@ import java.util.concurrent.atomic.AtomicLong
|
|
|
19
53
|
interface SseConnectionDelegate {
|
|
20
54
|
fun connectionDidOpen(response: Response, requestId: String)
|
|
21
55
|
fun connectionDidReceiveMessage(id: String?, type: String?, data: String, requestId: String)
|
|
22
|
-
fun
|
|
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) {}
|
|
23
66
|
fun connectionDidClose(requestId: String)
|
|
24
67
|
}
|
|
25
68
|
|
|
26
69
|
/**
|
|
27
|
-
*
|
|
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.
|
|
28
72
|
*/
|
|
29
|
-
class
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
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
|
+
}
|
|
35
108
|
}
|
|
109
|
+
isAtStreamStart = false
|
|
110
|
+
}
|
|
36
111
|
|
|
37
|
-
|
|
38
|
-
|
|
112
|
+
if (skipLeadingLf) {
|
|
113
|
+
skipLeadingLf = false
|
|
114
|
+
if (buffer.size > 0 && buffer[0] == '\n'.code.toByte()) {
|
|
115
|
+
buffer.skip(1)
|
|
39
116
|
}
|
|
117
|
+
}
|
|
40
118
|
|
|
41
|
-
|
|
42
|
-
|
|
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
|
|
43
142
|
}
|
|
44
143
|
|
|
45
|
-
|
|
46
|
-
|
|
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
|
+
}
|
|
47
245
|
}
|
|
48
246
|
}
|
|
49
|
-
return EventSources.createFactory(client).newEventSource(request, listener)
|
|
50
247
|
}
|
|
51
248
|
}
|
|
52
249
|
|
|
53
250
|
/**
|
|
54
|
-
*
|
|
55
|
-
* Runs at the network layer to capture true HTTP status, raw wire headers (e.g. Content-Encoding: gzip), and timing.
|
|
251
|
+
* Thread-safe EventSource implementation backed by OkHttp [Call] and sequential [SseEventReader].
|
|
56
252
|
*/
|
|
57
|
-
internal class
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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()
|
|
64
281
|
}
|
|
65
|
-
|
|
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
|
+
}
|
|
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
|
+
}
|
|
343
|
+
|
|
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
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
while (!isCancelled && reader.processNextEvent(callback)) {
|
|
370
|
+
// Read and dispatch events sequentially
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
if (!isCancelled) {
|
|
374
|
+
delegate.connectionDidClose(requestId)
|
|
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()
|
|
388
|
+
}
|
|
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
|
|
66
406
|
}
|
|
67
407
|
}
|
|
68
408
|
|
|
69
409
|
/**
|
|
70
|
-
*
|
|
71
|
-
* Inspects decompressed UTF-8 stream before EventSourceReader discards SSE comments (`:`).
|
|
72
|
-
*
|
|
73
|
-
* Placed as an OkHttp Application Interceptor (above BridgeInterceptor), allowing OkHttp
|
|
74
|
-
* to handle transparent gzip/deflate decompression naturally without requiring manual GzipSource
|
|
75
|
-
* wrapping or disabling compression with 'Accept-Encoding: identity'.
|
|
410
|
+
* Shared tracker recording raw network socket transport metrics from InspectorNetworkInterceptor.
|
|
76
411
|
*/
|
|
77
|
-
|
|
78
|
-
private val
|
|
79
|
-
private val
|
|
80
|
-
|
|
81
|
-
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>()
|
|
82
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
|
+
}
|
|
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 {
|
|
83
441
|
override fun intercept(chain: Interceptor.Chain): Response {
|
|
84
442
|
val request = chain.request()
|
|
85
443
|
val rid = request.tag(String::class.java)
|
|
86
444
|
val response = chain.proceed(request)
|
|
87
|
-
|
|
445
|
+
rid?.let {
|
|
446
|
+
NetworkInspector.reportResponseStart(it, request, response)
|
|
447
|
+
}
|
|
88
448
|
val responseBody = response.body
|
|
89
|
-
if (responseBody != null) {
|
|
90
|
-
val
|
|
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
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
val wrappedBody = object : ResponseBody() {
|
|
91
461
|
override fun contentType() = responseBody.contentType()
|
|
92
462
|
override fun contentLength() = responseBody.contentLength()
|
|
93
|
-
|
|
94
|
-
private val bufferedSource by lazy {
|
|
95
|
-
(object : ForwardingSource(responseBody.source()) {
|
|
96
|
-
private var isAtStartOfLine = true
|
|
97
|
-
private var isReadingComment = false
|
|
98
|
-
private val commentBuffer = java.io.ByteArrayOutputStream()
|
|
99
|
-
|
|
100
|
-
override fun read(sink: Buffer, byteCount: Long): Long {
|
|
101
|
-
val scratch = Buffer()
|
|
102
|
-
val bytesRead = super.read(scratch, byteCount)
|
|
103
|
-
if (bytesRead != -1L) {
|
|
104
|
-
totalBytesReceived?.addAndGet(bytesRead)
|
|
105
|
-
try {
|
|
106
|
-
val bytes = scratch.snapshot().toByteArray()
|
|
107
|
-
for (b in bytes) {
|
|
108
|
-
val isNewline = (b == '\n'.code.toByte() || b == '\r'.code.toByte())
|
|
109
|
-
if (isReadingComment) {
|
|
110
|
-
if (isNewline) {
|
|
111
|
-
isReadingComment = false
|
|
112
|
-
val rawComment = commentBuffer.toString("UTF-8")
|
|
113
|
-
// WHATWG SSE Spec: Remove only a single leading space after ':' if present
|
|
114
|
-
val commentText = if (rawComment.startsWith(" ")) rawComment.substring(1) else rawComment
|
|
115
|
-
commentBuffer.reset()
|
|
116
|
-
onHeartbeat(rid, commentText)
|
|
117
|
-
} else {
|
|
118
|
-
commentBuffer.write(b.toInt())
|
|
119
|
-
}
|
|
120
|
-
} else if (isAtStartOfLine && b == ':'.code.toByte()) {
|
|
121
|
-
isReadingComment = true
|
|
122
|
-
commentBuffer.reset()
|
|
123
|
-
}
|
|
124
|
-
isAtStartOfLine = isNewline
|
|
125
|
-
}
|
|
126
|
-
} catch (e: Exception) {
|
|
127
|
-
// Swallow byte scanning errors to prevent stream reader failure if buffer inspection fails
|
|
128
|
-
}
|
|
129
|
-
sink.write(scratch, bytesRead)
|
|
130
|
-
}
|
|
131
|
-
return bytesRead
|
|
132
|
-
}
|
|
133
|
-
}).buffer()
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
override fun source() = bufferedSource
|
|
463
|
+
override fun source(): BufferedSource = trackingSource.buffer()
|
|
137
464
|
}
|
|
138
|
-
return response.newBuilder().body(
|
|
465
|
+
return response.newBuilder().body(wrappedBody).build()
|
|
139
466
|
}
|
|
140
467
|
return response
|
|
141
468
|
}
|
|
142
469
|
}
|
|
143
470
|
|
|
144
|
-
|
|
145
|
-
message = "Use HeartbeatInterceptor instead. This interceptor is an OkHttp application interceptor, not a network interceptor.",
|
|
146
|
-
replaceWith = ReplaceWith("HeartbeatInterceptor")
|
|
147
|
-
)
|
|
148
|
-
internal typealias HeartbeatNetworkInterceptor = HeartbeatInterceptor
|
|
471
|
+
|
|
@@ -24,6 +24,10 @@ class SseEventBuffer(
|
|
|
24
24
|
private var batchingIntervalMs: Double = 0.0
|
|
25
25
|
private var maxBufferSize: Int = 1000
|
|
26
26
|
|
|
27
|
+
private var peakBufferedEvents: Int = 0
|
|
28
|
+
private var bufferFlushCount: Long = 0
|
|
29
|
+
private var bufferOverflowCount: Long = 0
|
|
30
|
+
|
|
27
31
|
private val flushRunnable = Runnable { flush() }
|
|
28
32
|
|
|
29
33
|
fun configure(batchingIntervalMs: Double, maxBufferSize: Int) {
|
|
@@ -39,17 +43,28 @@ class SseEventBuffer(
|
|
|
39
43
|
this.onFlush = {}
|
|
40
44
|
}
|
|
41
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
|
+
|
|
42
51
|
fun push(event: SseEvent) {
|
|
43
52
|
if (batchingIntervalMs <= 0.0) {
|
|
44
53
|
if (dispatcher == null || dispatcher.isCurrentDispatcher()) {
|
|
45
54
|
synchronized(eventBuffer) {
|
|
46
55
|
eventBuffer.add(event)
|
|
56
|
+
if (eventBuffer.size > peakBufferedEvents) {
|
|
57
|
+
peakBufferedEvents = eventBuffer.size
|
|
58
|
+
}
|
|
47
59
|
}
|
|
48
60
|
flush()
|
|
49
61
|
} else {
|
|
50
62
|
dispatcher.post {
|
|
51
63
|
synchronized(eventBuffer) {
|
|
52
64
|
eventBuffer.add(event)
|
|
65
|
+
if (eventBuffer.size > peakBufferedEvents) {
|
|
66
|
+
peakBufferedEvents = eventBuffer.size
|
|
67
|
+
}
|
|
53
68
|
}
|
|
54
69
|
flush()
|
|
55
70
|
}
|
|
@@ -60,7 +75,11 @@ class SseEventBuffer(
|
|
|
60
75
|
var shouldFlush = false
|
|
61
76
|
synchronized(eventBuffer) {
|
|
62
77
|
eventBuffer.add(event)
|
|
78
|
+
if (eventBuffer.size > peakBufferedEvents) {
|
|
79
|
+
peakBufferedEvents = eventBuffer.size
|
|
80
|
+
}
|
|
63
81
|
if (eventBuffer.size >= maxBufferSize) {
|
|
82
|
+
bufferOverflowCount++
|
|
64
83
|
shouldFlush = true
|
|
65
84
|
}
|
|
66
85
|
}
|
|
@@ -88,6 +107,7 @@ class SseEventBuffer(
|
|
|
88
107
|
isFlushPending.set(false)
|
|
89
108
|
return
|
|
90
109
|
}
|
|
110
|
+
bufferFlushCount++
|
|
91
111
|
eventsToEmit = eventBuffer.toTypedArray()
|
|
92
112
|
eventBuffer.clear()
|
|
93
113
|
isFlushPending.set(false)
|
|
@@ -34,6 +34,15 @@ class SseReconnectStrategy {
|
|
|
34
34
|
this.maxReconnectAttempts = if (maxReconnectAttempts == -1 || maxReconnectAttempts >= 0) maxReconnectAttempts else -1
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
/**
|
|
38
|
+
* Updates base retry interval when server sends a 'retry: <ms>' directive.
|
|
39
|
+
*/
|
|
40
|
+
fun updateRetryInterval(retryMs: Double) {
|
|
41
|
+
if (!retryMs.isNaN() && !retryMs.isInfinite() && retryMs >= 0) {
|
|
42
|
+
this.retryIntervalMs = retryMs
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
37
46
|
fun nextDelay(isError: Boolean): Long {
|
|
38
47
|
_currentReconnectAttempts.incrementAndGet()
|
|
39
48
|
val baseDelay = if (isError) {
|