react-native-nitro-sse 3.2.0-beta.1 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -27
- package/android/build.gradle +7 -3
- package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +8 -32
- package/android/src/main/java/com/margelo/nitro/nitrosse/NetworkInspector.kt +124 -6
- package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +439 -509
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +137 -316
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +18 -8
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventReader.kt +231 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseFailureClassifier.kt +245 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseMetrics.kt +237 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +13 -6
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +48 -22
- package/ios/NitroSse.swift +402 -484
- package/ios/SseConfig+CopyWith.swift +0 -2
- package/ios/SseConnectionHandler.swift +238 -446
- package/ios/SseDispatchQueueDispatcher.swift +7 -7
- package/ios/SseDispatcher.swift +5 -4
- package/ios/SseEventBuffer.swift +24 -23
- package/ios/SseEventParser.swift +360 -0
- package/ios/SseFailureClassifier.swift +249 -0
- package/ios/SseLifecycleManager.swift +19 -14
- package/ios/SseMetrics.swift +188 -0
- package/ios/SseNetworkMonitor.swift +18 -14
- package/ios/SseReconnectStrategy.swift +28 -30
- package/lib/module/FetchSseDriver.js +398 -170
- package/lib/module/MockSseEngine.js +15 -17
- package/lib/module/NitroSseClient.js +70 -56
- package/lib/module/SseConsoleLogger.js +64 -0
- package/lib/module/SseEventParser.js +173 -115
- package/lib/module/createNitroSse.js +7 -14
- package/lib/module/createNitroSse.native.js +2 -1
- package/lib/module/useNitroSse.js +103 -90
- package/lib/typescript/src/FetchSseDriver.d.ts +11 -4
- package/lib/typescript/src/MockSseEngine.d.ts +2 -2
- package/lib/typescript/src/NitroSse.nitro.d.ts +9 -1
- package/lib/typescript/src/NitroSseClient.d.ts +4 -1
- package/lib/typescript/src/SseConsoleLogger.d.ts +28 -0
- package/lib/typescript/src/SseEventParser.d.ts +18 -2
- package/lib/typescript/src/SseInterface.d.ts +21 -4
- package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.hpp +1 -1
- package/nitrogen/generated/android/c++/JFunc_void_std__vector_SseEvent_.hpp +1 -1
- package/nitrogen/generated/android/c++/JHttpMethod.hpp +1 -1
- package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +1 -1
- package/nitrogen/generated/android/c++/JHybridNitroSseSpec.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseConfig.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseDisconnectReason.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseEvent.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseEventType.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseMockConfig.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseMockEvent.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseMockMode.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseState.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseStats.hpp +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/Func_void_std__vector_SseEvent_.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HttpMethod.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HybridNitroSseSpec.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseDisconnectReason.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEvent.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEventType.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockConfig.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockEvent.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockMode.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseState.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseStats.kt +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/nitrosseOnLoad.kt +1 -1
- package/nitrogen/generated/android/nitrosse+autolinking.cmake +1 -1
- package/nitrogen/generated/android/nitrosse+autolinking.gradle +1 -1
- package/nitrogen/generated/android/nitrosseOnLoad.cpp +1 -1
- package/nitrogen/generated/android/nitrosseOnLoad.hpp +1 -1
- package/nitrogen/generated/ios/NitroSse+autolinking.rb +1 -1
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.cpp +1 -1
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +1 -1
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +1 -1
- package/nitrogen/generated/ios/NitroSseAutolinking.mm +1 -1
- package/nitrogen/generated/ios/NitroSseAutolinking.swift +1 -5
- package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.cpp +1 -1
- package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +1 -1
- package/nitrogen/generated/ios/swift/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.swift +1 -1
- package/nitrogen/generated/ios/swift/Func_void_std__exception_ptr.swift +1 -1
- package/nitrogen/generated/ios/swift/Func_void_std__shared_ptr_Promise_std__unordered_map_std__string__std__string___.swift +1 -1
- package/nitrogen/generated/ios/swift/Func_void_std__unordered_map_std__string__std__string_.swift +1 -1
- package/nitrogen/generated/ios/swift/Func_void_std__vector_SseEvent_.swift +1 -1
- package/nitrogen/generated/ios/swift/HttpMethod.swift +1 -1
- package/nitrogen/generated/ios/swift/HybridNitroSseSpec.swift +1 -1
- package/nitrogen/generated/ios/swift/HybridNitroSseSpec_cxx.swift +3 -3
- package/nitrogen/generated/ios/swift/SseConfig.swift +1 -1
- package/nitrogen/generated/ios/swift/SseDisconnectReason.swift +1 -1
- package/nitrogen/generated/ios/swift/SseEvent.swift +1 -1
- package/nitrogen/generated/ios/swift/SseEventType.swift +1 -1
- package/nitrogen/generated/ios/swift/SseMockConfig.swift +1 -1
- package/nitrogen/generated/ios/swift/SseMockEvent.swift +1 -1
- package/nitrogen/generated/ios/swift/SseMockMode.swift +1 -1
- package/nitrogen/generated/ios/swift/SseState.swift +1 -1
- package/nitrogen/generated/ios/swift/SseStats.swift +1 -1
- package/nitrogen/generated/shared/c++/HttpMethod.hpp +1 -1
- package/nitrogen/generated/shared/c++/HybridNitroSseSpec.cpp +1 -1
- package/nitrogen/generated/shared/c++/HybridNitroSseSpec.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseConfig.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseDisconnectReason.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseEvent.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseEventType.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseMockConfig.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseMockEvent.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseMockMode.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseState.hpp +1 -1
- package/nitrogen/generated/shared/c++/SseStats.hpp +1 -1
- package/package.json +18 -10
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
package com.margelo.nitro.nitrosse
|
|
2
|
+
|
|
3
|
+
import okio.BufferedSource
|
|
4
|
+
import okio.ByteString
|
|
5
|
+
import java.io.IOException
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Maximum bytes allowed for a single SSE line to prevent Out-Of-Memory errors.
|
|
9
|
+
*/
|
|
10
|
+
const val MAX_SSE_LINE_LENGTH = 16 * 1024 * 1024L
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Maximum characters allowed for accumulated event data to prevent Out-Of-Memory errors.
|
|
14
|
+
*/
|
|
15
|
+
const val MAX_SSE_EVENT_DATA_SIZE = 16 * 1024 * 1024
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* CRLF delimiter byte sequence (\r, \n) used for optimized line break scanning.
|
|
19
|
+
*/
|
|
20
|
+
private val CRLF_DELIMITERS = ByteString.of('\r'.code.toByte(), '\n'.code.toByte())
|
|
21
|
+
|
|
22
|
+
private const val UTF8_BOM_LENGTH = 3L
|
|
23
|
+
private const val BOM_BYTE_0: Byte = 0xEF.toByte()
|
|
24
|
+
private const val BOM_BYTE_1: Byte = 0xBB.toByte()
|
|
25
|
+
private const val BOM_BYTE_2: Byte = 0xBF.toByte()
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Exception indicating an SSE parser resource limit violation (line length or accumulated event data size).
|
|
29
|
+
* Typed counterpart of iOS NitroSse error codes -2002 / -2003; treated as fatal (no reconnect).
|
|
30
|
+
*/
|
|
31
|
+
internal class SseParserLimitException(override val message: String) : IOException(message)
|
|
32
|
+
|
|
33
|
+
private fun parseFieldPair(line: String): Pair<String, String> {
|
|
34
|
+
val colonIndex = line.indexOf(':')
|
|
35
|
+
if (colonIndex == -1) return line to ""
|
|
36
|
+
val field = line.substring(0, colonIndex)
|
|
37
|
+
val hasLeadingSpace = colonIndex + 1 < line.length && line[colonIndex + 1] == ' '
|
|
38
|
+
val valueStart = if (hasLeadingSpace) colonIndex + 2 else colonIndex + 1
|
|
39
|
+
val value = line.substring(valueStart)
|
|
40
|
+
return field to value
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Sequential line-by-line SSE parser complying with WHATWG Server-Sent Events specification.
|
|
45
|
+
* Ensures strict chronological ordering between data messages, comments, and directives.
|
|
46
|
+
*/
|
|
47
|
+
internal class SseEventReader(private val source: BufferedSource) {
|
|
48
|
+
interface Callback {
|
|
49
|
+
fun onEvent(id: String?, type: String?, data: String)
|
|
50
|
+
fun onComment(comment: String)
|
|
51
|
+
fun onRetryChange(retryMs: Long)
|
|
52
|
+
fun onIdUpdate(id: String?) {}
|
|
53
|
+
fun onLinesParsed(count: Int) {}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
private val dataBuffer = StringBuilder()
|
|
57
|
+
private var hasData = false
|
|
58
|
+
private var eventType: String? = null
|
|
59
|
+
private var lastEventId: String? = null
|
|
60
|
+
private var lastEventIdBuffer: String? = null
|
|
61
|
+
private var idUpdatedInCurrentEvent = false
|
|
62
|
+
private var isAtStreamStart = true
|
|
63
|
+
private var skipLeadingLf = false
|
|
64
|
+
|
|
65
|
+
private fun prepareBufferForRead(buffer: okio.Buffer) {
|
|
66
|
+
if (isAtStreamStart) {
|
|
67
|
+
val hasBom = source.request(UTF8_BOM_LENGTH) &&
|
|
68
|
+
buffer[0] == BOM_BYTE_0 &&
|
|
69
|
+
buffer[1] == BOM_BYTE_1 &&
|
|
70
|
+
buffer[2] == BOM_BYTE_2
|
|
71
|
+
if (hasBom) {
|
|
72
|
+
buffer.skip(UTF8_BOM_LENGTH)
|
|
73
|
+
}
|
|
74
|
+
isAtStreamStart = false
|
|
75
|
+
} else if (skipLeadingLf) {
|
|
76
|
+
skipLeadingLf = false
|
|
77
|
+
if (buffer[0] == '\n'.code.toByte()) {
|
|
78
|
+
buffer.skip(1)
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
private fun consumeLineAtIndex(buffer: okio.Buffer, newlineIndex: Long): String {
|
|
84
|
+
if (newlineIndex > MAX_SSE_LINE_LENGTH) {
|
|
85
|
+
throw SseParserLimitException("SSE line exceeded maximum limit of $MAX_SSE_LINE_LENGTH bytes")
|
|
86
|
+
}
|
|
87
|
+
val delimiterByte = buffer[newlineIndex]
|
|
88
|
+
val line = buffer.readUtf8(newlineIndex)
|
|
89
|
+
buffer.skip(1)
|
|
90
|
+
if (delimiterByte == '\r'.code.toByte()) {
|
|
91
|
+
// If followed immediately by \n in current buffer, consume \n as CRLF.
|
|
92
|
+
// If buffer is exhausted, defer check via skipLeadingLf to avoid blocking on bare CR.
|
|
93
|
+
if (buffer.size > 0) {
|
|
94
|
+
if (buffer[0] == '\n'.code.toByte()) {
|
|
95
|
+
buffer.skip(1)
|
|
96
|
+
}
|
|
97
|
+
} else {
|
|
98
|
+
skipLeadingLf = true
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return line
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
private fun findOrReadLine(buffer: okio.Buffer): String? {
|
|
105
|
+
var scanned = 0L
|
|
106
|
+
var newlineIndex = buffer.indexOfElement(CRLF_DELIMITERS, scanned)
|
|
107
|
+
while (newlineIndex == -1L) {
|
|
108
|
+
if (buffer.size > MAX_SSE_LINE_LENGTH) {
|
|
109
|
+
throw SseParserLimitException("SSE line exceeded maximum limit of $MAX_SSE_LINE_LENGTH bytes")
|
|
110
|
+
}
|
|
111
|
+
scanned = buffer.size
|
|
112
|
+
if (!source.request(buffer.size + 1)) {
|
|
113
|
+
return null
|
|
114
|
+
}
|
|
115
|
+
newlineIndex = buffer.indexOfElement(CRLF_DELIMITERS, scanned)
|
|
116
|
+
}
|
|
117
|
+
return consumeLineAtIndex(buffer, newlineIndex)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Reads a line from [source] handling CRLF (\r\n), bare CR (\r), and LF (\n).
|
|
122
|
+
* Strips leading UTF-8 BOM (0xEF, 0xBB, 0xBF) if present at stream start per WHATWG SSE spec.
|
|
123
|
+
* Operates on [BufferedSource.buffer] using hardware-accelerated [Buffer.indexOfElement] to locate
|
|
124
|
+
* line endings without byte-by-byte Kotlin loop overhead while properly supporting bare carriage returns.
|
|
125
|
+
*/
|
|
126
|
+
private fun readSseLine(): String? {
|
|
127
|
+
if (source.exhausted()) return null
|
|
128
|
+
val buffer = source.buffer
|
|
129
|
+
prepareBufferForRead(buffer)
|
|
130
|
+
return findOrReadLine(buffer)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
private fun handleEof(linesParsedInEvent: Int, callback: Callback) {
|
|
134
|
+
if (linesParsedInEvent > 0) {
|
|
135
|
+
callback.onLinesParsed(linesParsedInEvent)
|
|
136
|
+
}
|
|
137
|
+
dataBuffer.setLength(0)
|
|
138
|
+
hasData = false
|
|
139
|
+
eventType = null
|
|
140
|
+
lastEventIdBuffer = lastEventId
|
|
141
|
+
idUpdatedInCurrentEvent = false
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
private fun handleEmptyLine(linesParsedInEvent: Int, callback: Callback): Boolean {
|
|
145
|
+
if (idUpdatedInCurrentEvent) {
|
|
146
|
+
lastEventId = lastEventIdBuffer
|
|
147
|
+
idUpdatedInCurrentEvent = false
|
|
148
|
+
callback.onIdUpdate(lastEventId)
|
|
149
|
+
}
|
|
150
|
+
if (hasData) {
|
|
151
|
+
callback.onLinesParsed(linesParsedInEvent)
|
|
152
|
+
val data = dataBuffer.toString()
|
|
153
|
+
val id = lastEventId
|
|
154
|
+
val type = eventType
|
|
155
|
+
dataBuffer.setLength(0)
|
|
156
|
+
hasData = false
|
|
157
|
+
eventType = null
|
|
158
|
+
callback.onEvent(id, type, data)
|
|
159
|
+
return true
|
|
160
|
+
}
|
|
161
|
+
// WHATWG SSE: Dispatching an empty event still resets the event type buffer
|
|
162
|
+
eventType = null
|
|
163
|
+
return false
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
private fun appendDataField(value: String) {
|
|
167
|
+
// Account for the '\n' joining this line to the previous ones (parity with iOS / TypeScript).
|
|
168
|
+
val separatorSize = if (hasData) 1 else 0
|
|
169
|
+
if (dataBuffer.length + separatorSize + value.length > MAX_SSE_EVENT_DATA_SIZE) {
|
|
170
|
+
throw SseParserLimitException(
|
|
171
|
+
"SSE event data exceeded maximum limit of $MAX_SSE_EVENT_DATA_SIZE characters"
|
|
172
|
+
)
|
|
173
|
+
}
|
|
174
|
+
if (hasData) {
|
|
175
|
+
dataBuffer.append('\n')
|
|
176
|
+
}
|
|
177
|
+
dataBuffer.append(value)
|
|
178
|
+
hasData = true
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
private fun handleFieldLine(line: String, callback: Callback) {
|
|
182
|
+
val (field, value) = parseFieldPair(line)
|
|
183
|
+
when (field) {
|
|
184
|
+
"data" -> appendDataField(value)
|
|
185
|
+
"id" -> if (!value.contains('\u0000')) {
|
|
186
|
+
lastEventIdBuffer = if (value.isEmpty()) null else value
|
|
187
|
+
idUpdatedInCurrentEvent = true
|
|
188
|
+
}
|
|
189
|
+
"event" -> eventType = if (value.isEmpty()) null else value
|
|
190
|
+
"retry" -> if (value.isNotEmpty() && value.all { it in '0'..'9' }) {
|
|
191
|
+
// WHATWG SSE: If field value consists solely of ASCII digits 0-9, set reconnection time.
|
|
192
|
+
value.toLongOrNull()?.let { callback.onRetryChange(it) }
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
private fun processLine(line: String, linesParsedInEvent: Int, callback: Callback): Boolean = when {
|
|
198
|
+
line.isEmpty() -> handleEmptyLine(linesParsedInEvent, callback)
|
|
199
|
+
line.startsWith(":") -> {
|
|
200
|
+
callback.onLinesParsed(linesParsedInEvent)
|
|
201
|
+
val commentStart = if (line.length > 1 && line[1] == ' ') 2 else 1
|
|
202
|
+
callback.onComment(line.substring(commentStart))
|
|
203
|
+
true
|
|
204
|
+
}
|
|
205
|
+
else -> {
|
|
206
|
+
handleFieldLine(line, callback)
|
|
207
|
+
false
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Reads lines from source until one event (message or comment) is completed and dispatched.
|
|
213
|
+
* Returns true if an event was dispatched, or false on EOF.
|
|
214
|
+
* Per WHATWG SSE spec: "Once the end of the file is reached, any pending data must be discarded.
|
|
215
|
+
* (If the file ends in the middle of an event, before the final empty line,
|
|
216
|
+
* the incomplete event is not dispatched.)"
|
|
217
|
+
*/
|
|
218
|
+
fun processNextEvent(callback: Callback): Boolean {
|
|
219
|
+
var linesParsedInEvent = 0
|
|
220
|
+
var line = readSseLine()
|
|
221
|
+
while (line != null) {
|
|
222
|
+
linesParsedInEvent++
|
|
223
|
+
if (processLine(line, linesParsedInEvent, callback)) {
|
|
224
|
+
return true
|
|
225
|
+
}
|
|
226
|
+
line = readSseLine()
|
|
227
|
+
}
|
|
228
|
+
handleEof(linesParsedInEvent, callback)
|
|
229
|
+
return false
|
|
230
|
+
}
|
|
231
|
+
}
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
package com.margelo.nitro.nitrosse
|
|
2
|
+
|
|
3
|
+
import okhttp3.Response
|
|
4
|
+
import java.io.InterruptedIOException
|
|
5
|
+
import java.net.SocketTimeoutException
|
|
6
|
+
import kotlin.random.Random
|
|
7
|
+
|
|
8
|
+
internal object SseHttpStatus {
|
|
9
|
+
const val OK = 200
|
|
10
|
+
const val OK_DOUBLE = 200.0
|
|
11
|
+
const val NO_CONTENT = 204
|
|
12
|
+
const val NO_CONTENT_DOUBLE = 204.0
|
|
13
|
+
const val SUCCESS_MAX = 299
|
|
14
|
+
const val BAD_REQUEST = 400
|
|
15
|
+
const val UNAUTHORIZED = 401
|
|
16
|
+
const val FORBIDDEN = 403
|
|
17
|
+
const val REQUEST_TIMEOUT = 408
|
|
18
|
+
const val TOO_MANY_REQUESTS = 429
|
|
19
|
+
const val TOO_MANY_REQUESTS_DOUBLE = 429.0
|
|
20
|
+
const val CLIENT_ERROR_MAX = 499
|
|
21
|
+
const val INTERNAL_ERROR = 500
|
|
22
|
+
const val SERVICE_UNAVAILABLE = 503
|
|
23
|
+
const val UNKNOWN = -1
|
|
24
|
+
const val UNKNOWN_DOUBLE = -1.0
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
internal data class SseFailureContext(
|
|
28
|
+
val throwable: Throwable?,
|
|
29
|
+
val response: Response?,
|
|
30
|
+
val errorBody: String?,
|
|
31
|
+
val statusCode: Int,
|
|
32
|
+
val isTimeout: Boolean,
|
|
33
|
+
val isParserLimit: Boolean,
|
|
34
|
+
val isInvalidContentType: Boolean
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
internal data class SseFailurePolicyInput(
|
|
38
|
+
val hasInterceptor: Boolean,
|
|
39
|
+
val nextAuthAttempt: Int,
|
|
40
|
+
val maxAuthRetries: Int,
|
|
41
|
+
val maxRetryIntervalMs: Long,
|
|
42
|
+
val retryAfterJitterMs: Long = defaultRetryAfterJitterMs()
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
private const val RETRY_AFTER_JITTER_BASE_MS = 500
|
|
46
|
+
private const val RETRY_AFTER_JITTER_BOUND_MS = 1001
|
|
47
|
+
private const val MILLIS_PER_SECOND = 1000L
|
|
48
|
+
|
|
49
|
+
private fun defaultRetryAfterJitterMs(): Long =
|
|
50
|
+
(RETRY_AFTER_JITTER_BASE_MS + Random.nextInt(RETRY_AFTER_JITTER_BOUND_MS)).toLong()
|
|
51
|
+
|
|
52
|
+
private fun isTimeoutThrowable(t: Throwable?): Boolean =
|
|
53
|
+
t is SocketTimeoutException ||
|
|
54
|
+
t is InterruptedIOException ||
|
|
55
|
+
t?.message?.contains("timeout", ignoreCase = true) == true
|
|
56
|
+
|
|
57
|
+
private const val MAX_ERROR_MESSAGE_BODY_CHARS = 256
|
|
58
|
+
|
|
59
|
+
private fun formatErrorBodyPreview(errorBody: String?): String? {
|
|
60
|
+
val trimmed = errorBody?.trim()?.ifEmpty { null } ?: return null
|
|
61
|
+
return if (trimmed.length > MAX_ERROR_MESSAGE_BODY_CHARS) {
|
|
62
|
+
"${trimmed.take(MAX_ERROR_MESSAGE_BODY_CHARS)}…"
|
|
63
|
+
} else {
|
|
64
|
+
trimmed
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
private fun formatTransientErrorMessage(
|
|
69
|
+
t: Throwable?,
|
|
70
|
+
statusCode: Int,
|
|
71
|
+
reportedStatusCode: Double?,
|
|
72
|
+
errorBody: String?
|
|
73
|
+
): String {
|
|
74
|
+
val bodyPreview = if (statusCode >= SseHttpStatus.INTERNAL_ERROR) {
|
|
75
|
+
formatErrorBodyPreview(errorBody)
|
|
76
|
+
} else {
|
|
77
|
+
null
|
|
78
|
+
}
|
|
79
|
+
return when {
|
|
80
|
+
bodyPreview != null -> "Server Error ($statusCode): $bodyPreview"
|
|
81
|
+
else -> t?.message ?: if (reportedStatusCode != null) {
|
|
82
|
+
"Link lost (${reportedStatusCode.toInt()})"
|
|
83
|
+
} else {
|
|
84
|
+
"Link lost"
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
internal sealed class SseFailureDecision {
|
|
90
|
+
data class FailAndStop(val message: String, val statusCode: Double?) : SseFailureDecision()
|
|
91
|
+
data class AuthLimitReached(val message: String, val statusCode: Double) : SseFailureDecision()
|
|
92
|
+
data class AuthRetry(val message: String, val statusCode: Double) : SseFailureDecision()
|
|
93
|
+
data class RetryAfter(val message: String, val statusCode: Double, val delayMs: Long) : SseFailureDecision()
|
|
94
|
+
data class RateLimitBackoff(val message: String, val statusCode: Double) : SseFailureDecision()
|
|
95
|
+
data class TransientRetry(
|
|
96
|
+
val message: String,
|
|
97
|
+
val statusCode: Double?,
|
|
98
|
+
val markStale: Boolean
|
|
99
|
+
) : SseFailureDecision()
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Pure classifier mapping OkHttp/parser failures into disconnect metrics and reconnection decisions.
|
|
104
|
+
*/
|
|
105
|
+
internal object SseFailureClassifier {
|
|
106
|
+
fun isEventStreamContentType(contentTypeHeader: String?): Boolean {
|
|
107
|
+
val rawMime = contentTypeHeader?.substringBefore(';')?.trim()?.lowercase()
|
|
108
|
+
return rawMime == "text/event-stream"
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
fun isInvalidEventStreamResponse(t: Throwable?, response: Response?): Boolean {
|
|
112
|
+
val hasInvalidBodyType = response != null &&
|
|
113
|
+
response.code in SseHttpStatus.OK..SseHttpStatus.SUCCESS_MAX &&
|
|
114
|
+
!isEventStreamContentType(response.header("Content-Type"))
|
|
115
|
+
return t is InvalidContentTypeException || hasInvalidBodyType
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
fun buildContext(t: Throwable?, response: Response?, errorBody: String?): SseFailureContext =
|
|
119
|
+
SseFailureContext(
|
|
120
|
+
throwable = t,
|
|
121
|
+
response = response,
|
|
122
|
+
errorBody = errorBody,
|
|
123
|
+
statusCode = response?.code ?: SseHttpStatus.UNKNOWN,
|
|
124
|
+
isTimeout = isTimeoutThrowable(t),
|
|
125
|
+
isParserLimit = t is SseParserLimitException,
|
|
126
|
+
isInvalidContentType = isInvalidEventStreamResponse(t, response)
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
fun disconnectReason(context: SseFailureContext): SseDisconnectReason = when {
|
|
130
|
+
context.statusCode >= SseHttpStatus.BAD_REQUEST ||
|
|
131
|
+
context.statusCode == SseHttpStatus.NO_CONTENT ||
|
|
132
|
+
context.isInvalidContentType -> SseDisconnectReason.SERVER_ERROR
|
|
133
|
+
context.isParserLimit -> SseDisconnectReason.PARSER_ERROR
|
|
134
|
+
context.isTimeout -> SseDisconnectReason.TIMEOUT
|
|
135
|
+
else -> SseDisconnectReason.NETWORK_ERROR
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
fun errorCodeString(context: SseFailureContext): String =
|
|
139
|
+
context.throwable?.javaClass?.simpleName ?: context.statusCode.toString()
|
|
140
|
+
|
|
141
|
+
fun classify(context: SseFailureContext, policy: SseFailurePolicyInput): SseFailureDecision =
|
|
142
|
+
classifyTerminal(context)
|
|
143
|
+
?: classifyAuth(context.statusCode, policy)
|
|
144
|
+
?: classifyRetryAfterOrRateLimit(context, policy)
|
|
145
|
+
?: buildTransientRetry(context)
|
|
146
|
+
|
|
147
|
+
private fun classifyTerminal(context: SseFailureContext): SseFailureDecision? {
|
|
148
|
+
val statusCode = context.statusCode
|
|
149
|
+
val statusDouble = if (statusCode != SseHttpStatus.UNKNOWN) statusCode.toDouble() else null
|
|
150
|
+
val isFatalClientError = statusCode in SseHttpStatus.BAD_REQUEST..SseHttpStatus.CLIENT_ERROR_MAX &&
|
|
151
|
+
statusCode != SseHttpStatus.UNAUTHORIZED &&
|
|
152
|
+
statusCode != SseHttpStatus.FORBIDDEN &&
|
|
153
|
+
statusCode != SseHttpStatus.REQUEST_TIMEOUT &&
|
|
154
|
+
statusCode != SseHttpStatus.TOO_MANY_REQUESTS
|
|
155
|
+
|
|
156
|
+
return when {
|
|
157
|
+
statusCode == SseHttpStatus.NO_CONTENT ->
|
|
158
|
+
SseFailureDecision.FailAndStop("No Content (204). Stopping.", SseHttpStatus.NO_CONTENT_DOUBLE)
|
|
159
|
+
context.isInvalidContentType ->
|
|
160
|
+
SseFailureDecision.FailAndStop(
|
|
161
|
+
"Invalid Content-Type: expected text/event-stream. Stopping.",
|
|
162
|
+
statusDouble
|
|
163
|
+
)
|
|
164
|
+
statusCode in SseHttpStatus.OK..SseHttpStatus.SUCCESS_MAX && statusCode != SseHttpStatus.OK ->
|
|
165
|
+
SseFailureDecision.FailAndStop(
|
|
166
|
+
"HTTP $statusCode is not a valid SSE response. Stopping.",
|
|
167
|
+
statusDouble
|
|
168
|
+
)
|
|
169
|
+
context.throwable is SseParserLimitException ->
|
|
170
|
+
// Parser resource violations (line length, event data size) are fatal and must not reconnect
|
|
171
|
+
SseFailureDecision.FailAndStop(context.throwable.message, statusDouble)
|
|
172
|
+
isFatalClientError -> {
|
|
173
|
+
val bodyPreview = formatErrorBodyPreview(context.errorBody)
|
|
174
|
+
val finalMessage = if (bodyPreview != null) {
|
|
175
|
+
"Fatal Error ($statusCode): $bodyPreview"
|
|
176
|
+
} else {
|
|
177
|
+
"Fatal Error ($statusCode). Stopping."
|
|
178
|
+
}
|
|
179
|
+
SseFailureDecision.FailAndStop(finalMessage, statusCode.toDouble())
|
|
180
|
+
}
|
|
181
|
+
else -> null
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
private fun classifyAuth(statusCode: Int, policy: SseFailurePolicyInput): SseFailureDecision? = when {
|
|
186
|
+
statusCode != SseHttpStatus.UNAUTHORIZED && statusCode != SseHttpStatus.FORBIDDEN -> null
|
|
187
|
+
!policy.hasInterceptor -> SseFailureDecision.FailAndStop(
|
|
188
|
+
"Auth Error ($statusCode) - No interceptor provided. Stopping.",
|
|
189
|
+
statusCode.toDouble()
|
|
190
|
+
)
|
|
191
|
+
policy.nextAuthAttempt > policy.maxAuthRetries -> SseFailureDecision.AuthLimitReached(
|
|
192
|
+
"Auth Error ($statusCode) - Retry limit reached (${policy.maxAuthRetries}). Stopping.",
|
|
193
|
+
statusCode.toDouble()
|
|
194
|
+
)
|
|
195
|
+
else -> SseFailureDecision.AuthRetry(
|
|
196
|
+
"Auth Error ($statusCode) - Retry ${policy.nextAuthAttempt}/${policy.maxAuthRetries}. Refreshing token...",
|
|
197
|
+
statusCode.toDouble()
|
|
198
|
+
)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private fun classifyRetryAfterOrRateLimit(
|
|
202
|
+
context: SseFailureContext,
|
|
203
|
+
policy: SseFailurePolicyInput
|
|
204
|
+
): SseFailureDecision? {
|
|
205
|
+
val statusCode = context.statusCode
|
|
206
|
+
val retryAfterMillis = SseReconnectStrategy.extractRetryAfterMillis(context.response)
|
|
207
|
+
val isRetryAfterStatus = statusCode == SseHttpStatus.TOO_MANY_REQUESTS ||
|
|
208
|
+
statusCode == SseHttpStatus.SERVICE_UNAVAILABLE
|
|
209
|
+
|
|
210
|
+
return when {
|
|
211
|
+
isRetryAfterStatus && retryAfterMillis != null -> {
|
|
212
|
+
val boundedRetryAfter = retryAfterMillis.coerceIn(0L, policy.maxRetryIntervalMs)
|
|
213
|
+
val totalDelay = (boundedRetryAfter + policy.retryAfterJitterMs).coerceAtLeast(MILLIS_PER_SECOND)
|
|
214
|
+
SseFailureDecision.RetryAfter(
|
|
215
|
+
message = "Retry-After received: ${totalDelay / MILLIS_PER_SECOND}s",
|
|
216
|
+
statusCode = statusCode.toDouble(),
|
|
217
|
+
delayMs = totalDelay
|
|
218
|
+
)
|
|
219
|
+
}
|
|
220
|
+
statusCode == SseHttpStatus.TOO_MANY_REQUESTS ->
|
|
221
|
+
SseFailureDecision.RateLimitBackoff(
|
|
222
|
+
message = "Rate Limited (429). Retrying with backoff...",
|
|
223
|
+
statusCode = SseHttpStatus.TOO_MANY_REQUESTS_DOUBLE
|
|
224
|
+
)
|
|
225
|
+
else -> null
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
private fun buildTransientRetry(context: SseFailureContext): SseFailureDecision.TransientRetry {
|
|
230
|
+
val statusCode = context.statusCode
|
|
231
|
+
val isReportedCode = statusCode >= SseHttpStatus.BAD_REQUEST
|
|
232
|
+
val reportedStatusCode = if (isReportedCode) statusCode.toDouble() else null
|
|
233
|
+
val defaultErrorMsg = formatTransientErrorMessage(
|
|
234
|
+
t = context.throwable,
|
|
235
|
+
statusCode = statusCode,
|
|
236
|
+
reportedStatusCode = reportedStatusCode,
|
|
237
|
+
errorBody = context.errorBody
|
|
238
|
+
)
|
|
239
|
+
return SseFailureDecision.TransientRetry(
|
|
240
|
+
message = defaultErrorMsg,
|
|
241
|
+
statusCode = reportedStatusCode,
|
|
242
|
+
markStale = context.isTimeout
|
|
243
|
+
)
|
|
244
|
+
}
|
|
245
|
+
}
|