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
|
@@ -3,7 +3,6 @@
|
|
|
3
3
|
import { SseEventParser } from "./SseEventParser.js";
|
|
4
4
|
import { MockSseEngine } from "./MockSseEngine.js";
|
|
5
5
|
function getUtf8ByteCount(str) {
|
|
6
|
-
if (!str) return 0;
|
|
7
6
|
let bytes = 0;
|
|
8
7
|
for (let i = 0; i < str.length; i++) {
|
|
9
8
|
const code = str.charCodeAt(i);
|
|
@@ -11,7 +10,7 @@ function getUtf8ByteCount(str) {
|
|
|
11
10
|
bytes += 1;
|
|
12
11
|
} else if (code <= 0x7ff) {
|
|
13
12
|
bytes += 2;
|
|
14
|
-
} else if (code >= 0xd800 && code <= 0xdbff) {
|
|
13
|
+
} else if (code >= 0xd800 && code <= 0xdbff && i + 1 < str.length && str.charCodeAt(i + 1) >= 0xdc00 && str.charCodeAt(i + 1) <= 0xdfff) {
|
|
15
14
|
bytes += 4;
|
|
16
15
|
i++;
|
|
17
16
|
} else {
|
|
@@ -20,6 +19,24 @@ function getUtf8ByteCount(str) {
|
|
|
20
19
|
}
|
|
21
20
|
return bytes;
|
|
22
21
|
}
|
|
22
|
+
function isValidNonNegative(val) {
|
|
23
|
+
return typeof val === 'number' && Number.isFinite(val) && val >= 0;
|
|
24
|
+
}
|
|
25
|
+
const DEFAULT_MAX_BUFFER_SIZE = 1000;
|
|
26
|
+
/** Hard upper bound on buffered events, matching SseEventBuffer on Android (Kotlin) and iOS (Swift). */
|
|
27
|
+
const HARD_MAX_BUFFER_SIZE = 10_000;
|
|
28
|
+
/** Maximum UTF-8 bytes to read from HTTP error responses, matching native 8KB cap. */
|
|
29
|
+
const MAX_ERROR_BODY_BYTES = 8192;
|
|
30
|
+
/** Maximum characters of error body preview included in `event.message` (`event.data` retains the full 8KB body). */
|
|
31
|
+
const MAX_ERROR_MESSAGE_BODY_CHARS = 256;
|
|
32
|
+
function formatErrorBodyPreview(errorBody) {
|
|
33
|
+
const trimmed = errorBody?.trim();
|
|
34
|
+
if (!trimmed) return undefined;
|
|
35
|
+
return trimmed.length > MAX_ERROR_MESSAGE_BODY_CHARS ? `${trimmed.slice(0, MAX_ERROR_MESSAGE_BODY_CHARS)}…` : trimmed;
|
|
36
|
+
}
|
|
37
|
+
function resolveMaxBufferSize(val) {
|
|
38
|
+
return typeof val === 'number' && Number.isFinite(val) && val > 0 ? Math.min(Math.floor(val), HARD_MAX_BUFFER_SIZE) : DEFAULT_MAX_BUFFER_SIZE;
|
|
39
|
+
}
|
|
23
40
|
|
|
24
41
|
/**
|
|
25
42
|
* Calculates exponential backoff with full symmetric jitter matching iOS/Android.
|
|
@@ -32,27 +49,30 @@ class SseReconnectStrategy {
|
|
|
32
49
|
_jitterFactor = 0.5;
|
|
33
50
|
_maxReconnectAttempts = -1;
|
|
34
51
|
configure(retryIntervalMs, maxRetryIntervalMs, jitterFactor, maxReconnectAttempts) {
|
|
35
|
-
if (
|
|
52
|
+
if (isValidNonNegative(retryIntervalMs)) {
|
|
36
53
|
this._retryInterval = retryIntervalMs / 1000.0;
|
|
37
54
|
} else {
|
|
38
55
|
this._retryInterval = 1.0;
|
|
39
56
|
}
|
|
40
|
-
if (
|
|
57
|
+
if (isValidNonNegative(maxRetryIntervalMs)) {
|
|
41
58
|
this._maxRetryInterval = maxRetryIntervalMs / 1000.0;
|
|
42
59
|
} else {
|
|
43
60
|
this._maxRetryInterval = 30.0;
|
|
44
61
|
}
|
|
45
|
-
if (jitterFactor
|
|
62
|
+
if (typeof jitterFactor === 'number' && Number.isFinite(jitterFactor)) {
|
|
46
63
|
this._jitterFactor = Math.min(Math.max(0.0, jitterFactor), 1.0);
|
|
47
64
|
} else {
|
|
48
65
|
this._jitterFactor = 0.5;
|
|
49
66
|
}
|
|
50
|
-
if (
|
|
67
|
+
if (isValidNonNegative(maxReconnectAttempts)) {
|
|
51
68
|
this._maxReconnectAttempts = maxReconnectAttempts;
|
|
52
69
|
} else {
|
|
53
70
|
this._maxReconnectAttempts = -1;
|
|
54
71
|
}
|
|
55
72
|
}
|
|
73
|
+
get maxReconnectAttempts() {
|
|
74
|
+
return this._maxReconnectAttempts;
|
|
75
|
+
}
|
|
56
76
|
hasReachedMaxAttempts() {
|
|
57
77
|
if (this._maxReconnectAttempts === -1) return false;
|
|
58
78
|
return this._currentReconnectAttempts >= this._maxReconnectAttempts;
|
|
@@ -62,27 +82,21 @@ class SseReconnectStrategy {
|
|
|
62
82
|
}
|
|
63
83
|
nextDelayMs(isError) {
|
|
64
84
|
this._currentReconnectAttempts++;
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
const base = Math.min(this._retryInterval * Math.pow(2.0, exponent), this._maxRetryInterval);
|
|
69
|
-
this._backoffCounter++;
|
|
70
|
-
const randomFactor = 1.0 - this._jitterFactor + Math.random() * (2 * this._jitterFactor);
|
|
71
|
-
delay = base * randomFactor;
|
|
72
|
-
} else {
|
|
73
|
-
const randomFactor = 1.0 - this._jitterFactor + Math.random() * (2 * this._jitterFactor);
|
|
74
|
-
delay = this._retryInterval * randomFactor;
|
|
75
|
-
}
|
|
85
|
+
const base = isError ? Math.min(this._retryInterval * Math.pow(2.0, this._backoffCounter++), this._maxRetryInterval) : Math.min(this._retryInterval, this._maxRetryInterval);
|
|
86
|
+
const randomFactor = 1.0 - this._jitterFactor + Math.random() * (2 * this._jitterFactor);
|
|
87
|
+
const delay = base * randomFactor;
|
|
76
88
|
|
|
77
|
-
// Minimum floor of 1000ms enforced across all platforms
|
|
78
|
-
|
|
89
|
+
// Minimum floor of 1000ms enforced across all platforms, capped at max 32-bit signed int for timer safety
|
|
90
|
+
const MAX_TIMER_MS = 2_147_483_647;
|
|
91
|
+
const ms = Number.isFinite(delay) ? delay * 1000.0 : MAX_TIMER_MS;
|
|
92
|
+
return Math.min(Math.max(ms, 1000.0), MAX_TIMER_MS);
|
|
79
93
|
}
|
|
80
94
|
reset() {
|
|
81
95
|
this._backoffCounter = 0;
|
|
82
96
|
this._currentReconnectAttempts = 0;
|
|
83
97
|
}
|
|
84
98
|
updateRetryInterval(retryMs) {
|
|
85
|
-
if (
|
|
99
|
+
if (isValidNonNegative(retryMs)) {
|
|
86
100
|
this._retryInterval = retryMs / 1000.0;
|
|
87
101
|
}
|
|
88
102
|
}
|
|
@@ -101,6 +115,7 @@ export class FetchSseDriver {
|
|
|
101
115
|
_batchBuffer = [];
|
|
102
116
|
_wasRunningBeforeNetworkLoss = false;
|
|
103
117
|
_reconnectStrategy = new SseReconnectStrategy();
|
|
118
|
+
|
|
104
119
|
// === Stats tracking ===
|
|
105
120
|
_rawBytesReceived = 0;
|
|
106
121
|
_totalBytesReceived = 0;
|
|
@@ -155,7 +170,7 @@ export class FetchSseDriver {
|
|
|
155
170
|
this._consecutiveAuthErrors = 0;
|
|
156
171
|
this._connectionAttemptVersion++;
|
|
157
172
|
this._updateState('connecting');
|
|
158
|
-
this._establishConnection(this._connectionAttemptVersion);
|
|
173
|
+
this._establishConnection(this._connectionAttemptVersion, this._config);
|
|
159
174
|
}
|
|
160
175
|
return;
|
|
161
176
|
}
|
|
@@ -165,12 +180,13 @@ export class FetchSseDriver {
|
|
|
165
180
|
this._consecutiveAuthErrors = 0;
|
|
166
181
|
this._reconnectStrategy.reset();
|
|
167
182
|
this._connectionAttemptVersion++;
|
|
168
|
-
this._establishConnection(this._connectionAttemptVersion);
|
|
183
|
+
this._establishConnection(this._connectionAttemptVersion, this._config);
|
|
169
184
|
}
|
|
170
185
|
stop() {
|
|
171
|
-
if (this._isRunning) {
|
|
186
|
+
if (this._isRunning || this._wasRunningBeforeNetworkLoss) {
|
|
172
187
|
this._disconnectReason = 'user_stop';
|
|
173
188
|
}
|
|
189
|
+
this._wasRunningBeforeNetworkLoss = false;
|
|
174
190
|
this._stopInternal(true);
|
|
175
191
|
}
|
|
176
192
|
restart() {
|
|
@@ -178,13 +194,14 @@ export class FetchSseDriver {
|
|
|
178
194
|
return;
|
|
179
195
|
}
|
|
180
196
|
this._connectedAt = undefined;
|
|
181
|
-
this.
|
|
182
|
-
this._cleanupTransport();
|
|
183
|
-
this._flushBatch();
|
|
197
|
+
this._teardownConnection();
|
|
184
198
|
this._isRunning = true;
|
|
199
|
+
this._isReconnecting = true;
|
|
200
|
+
this._consecutiveAuthErrors = 0;
|
|
201
|
+
this._reconnectStrategy.reset();
|
|
185
202
|
this._connectionAttemptVersion++;
|
|
186
203
|
this._updateState('reconnecting');
|
|
187
|
-
this._establishConnection(this._connectionAttemptVersion);
|
|
204
|
+
this._establishConnection(this._connectionAttemptVersion, this._config);
|
|
188
205
|
}
|
|
189
206
|
flush() {
|
|
190
207
|
this._flushBatch();
|
|
@@ -240,27 +257,33 @@ export class FetchSseDriver {
|
|
|
240
257
|
dispose() {
|
|
241
258
|
this.stop();
|
|
242
259
|
this._teardownNetworkListeners();
|
|
243
|
-
this._batchBuffer = [];
|
|
244
260
|
}
|
|
245
261
|
|
|
246
262
|
// =========================================================================
|
|
247
263
|
// Internal Connection Engine
|
|
248
264
|
// =========================================================================
|
|
249
265
|
|
|
250
|
-
|
|
251
|
-
|
|
266
|
+
/**
|
|
267
|
+
* A connection attempt is stale when the driver has been stopped, or when a
|
|
268
|
+
* newer attempt (reconnect / restart / stop) has superseded it.
|
|
269
|
+
*/
|
|
270
|
+
_isStale(attemptVersion) {
|
|
271
|
+
return !this._isRunning || attemptVersion !== this._connectionAttemptVersion;
|
|
272
|
+
}
|
|
273
|
+
async _establishConnection(attemptVersion, config) {
|
|
274
|
+
if (this._isStale(attemptVersion)) {
|
|
252
275
|
return;
|
|
253
276
|
}
|
|
254
277
|
this._updateState('connecting');
|
|
255
278
|
this._connectionAttempts++;
|
|
256
|
-
|
|
279
|
+
const attemptStartTime = Date.now();
|
|
257
280
|
this._timeToFirstByteMs = undefined;
|
|
258
281
|
|
|
259
282
|
// 1. Prepare dynamic headers via interceptor if configured
|
|
260
283
|
let dynamicInterceptorHeaders = {};
|
|
261
284
|
if (this._onBeforeRequest) {
|
|
262
285
|
try {
|
|
263
|
-
const timeoutMs =
|
|
286
|
+
const timeoutMs = config.connectionTimeoutMs ?? 15000;
|
|
264
287
|
let interceptorTimer;
|
|
265
288
|
try {
|
|
266
289
|
dynamicInterceptorHeaders = await Promise.race([this._onBeforeRequest(), new Promise((_, reject) => {
|
|
@@ -272,30 +295,43 @@ export class FetchSseDriver {
|
|
|
272
295
|
}
|
|
273
296
|
}
|
|
274
297
|
} catch (err) {
|
|
275
|
-
if (
|
|
298
|
+
if (this._isStale(attemptVersion)) return;
|
|
276
299
|
this._recordError('Interceptor Error', undefined);
|
|
277
|
-
|
|
300
|
+
const errorMsg = `Interceptor Error: ${err instanceof Error ? err.message : String(err)}`;
|
|
301
|
+
this._pushEvent({
|
|
302
|
+
type: 'error',
|
|
303
|
+
statusCode: -1,
|
|
304
|
+
message: errorMsg
|
|
305
|
+
});
|
|
306
|
+
this._consecutiveAuthErrors++;
|
|
307
|
+
const maxAuthRetries = config.maxAuthRetries ?? 3;
|
|
308
|
+
if (this._consecutiveAuthErrors > maxAuthRetries) {
|
|
309
|
+
this._disconnectReason = 'server_error';
|
|
310
|
+
this._failAndStop(`Auth retry limit reached (${maxAuthRetries}). Stopping.`, -1);
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
this._scheduleReconnect(true, undefined, attemptVersion, config);
|
|
278
314
|
return;
|
|
279
315
|
}
|
|
280
316
|
}
|
|
281
|
-
if (
|
|
317
|
+
if (this._isStale(attemptVersion)) return;
|
|
282
318
|
|
|
283
319
|
// URL syntax and protocol validation matching Native (http/https only)
|
|
284
320
|
try {
|
|
285
|
-
const parsedUrl = new URL(
|
|
321
|
+
const parsedUrl = new URL(config.url, typeof window !== 'undefined' && window.location ? window.location.href : 'http://localhost');
|
|
286
322
|
if (!['http:', 'https:'].includes(parsedUrl.protocol)) {
|
|
287
|
-
this._failAndStop(`Invalid URL: ${
|
|
323
|
+
this._failAndStop(`Invalid URL: ${config.url}`, -1);
|
|
288
324
|
return;
|
|
289
325
|
}
|
|
290
326
|
} catch {
|
|
291
|
-
this._failAndStop(`Invalid URL: ${
|
|
327
|
+
this._failAndStop(`Invalid URL: ${config.url}`, -1);
|
|
292
328
|
return;
|
|
293
329
|
}
|
|
294
330
|
|
|
295
331
|
// 2. Build headers
|
|
296
332
|
const filteredHeaders = {};
|
|
297
333
|
for (const [k, v] of Object.entries({
|
|
298
|
-
...(
|
|
334
|
+
...(config.headers ?? {}),
|
|
299
335
|
...this._dynamicHeaders,
|
|
300
336
|
...dynamicInterceptorHeaders
|
|
301
337
|
})) {
|
|
@@ -309,19 +345,27 @@ export class FetchSseDriver {
|
|
|
309
345
|
'Cache-Control': 'no-cache',
|
|
310
346
|
...filteredHeaders
|
|
311
347
|
};
|
|
312
|
-
if (this._lastProcessedId
|
|
348
|
+
if (this._lastProcessedId) {
|
|
313
349
|
mergedHeaders['Last-Event-ID'] = this._lastProcessedId;
|
|
314
350
|
}
|
|
315
351
|
const abortController = new AbortController();
|
|
316
352
|
this._abortController = abortController;
|
|
317
|
-
const connectionTimeoutMs =
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
353
|
+
const connectionTimeoutMs = config.connectionTimeoutMs ?? 15000;
|
|
354
|
+
const requestStartTime = Date.now();
|
|
355
|
+
let connectionTimer;
|
|
356
|
+
if (connectionTimeoutMs > 0) {
|
|
357
|
+
connectionTimer = setTimeout(() => {
|
|
358
|
+
if (this._connectionTimer === connectionTimer) {
|
|
359
|
+
this._connectionTimer = undefined;
|
|
360
|
+
}
|
|
361
|
+
if (attemptVersion === this._connectionAttemptVersion) {
|
|
362
|
+
this._disconnectReason = 'timeout';
|
|
363
|
+
abortController.abort();
|
|
364
|
+
}
|
|
365
|
+
}, connectionTimeoutMs);
|
|
366
|
+
this._connectionTimer = connectionTimer;
|
|
367
|
+
}
|
|
368
|
+
const method = (config.method ?? 'get').toUpperCase();
|
|
325
369
|
const fetchOptions = {
|
|
326
370
|
method,
|
|
327
371
|
headers: mergedHeaders,
|
|
@@ -329,21 +373,24 @@ export class FetchSseDriver {
|
|
|
329
373
|
mode: 'cors',
|
|
330
374
|
credentials: 'same-origin'
|
|
331
375
|
};
|
|
332
|
-
if (method === 'POST') {
|
|
376
|
+
if (method === 'POST' && config.body) {
|
|
377
|
+
fetchOptions.body = config.body;
|
|
333
378
|
const hasContentType = Object.keys(mergedHeaders).some(k => k.toLowerCase() === 'content-type');
|
|
334
|
-
if (!hasContentType
|
|
379
|
+
if (!hasContentType) {
|
|
335
380
|
mergedHeaders['Content-Type'] = 'application/json';
|
|
336
381
|
}
|
|
337
|
-
if (this._config.body) {
|
|
338
|
-
fetchOptions.body = this._config.body;
|
|
339
|
-
}
|
|
340
382
|
}
|
|
341
383
|
let response;
|
|
342
384
|
try {
|
|
343
|
-
response = await fetch(
|
|
385
|
+
response = await fetch(config.url, fetchOptions);
|
|
344
386
|
} catch (err) {
|
|
345
|
-
|
|
346
|
-
|
|
387
|
+
if (connectionTimer !== undefined) {
|
|
388
|
+
clearTimeout(connectionTimer);
|
|
389
|
+
if (this._connectionTimer === connectionTimer) {
|
|
390
|
+
this._connectionTimer = undefined;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
if (this._isStale(attemptVersion)) return;
|
|
347
394
|
const isAborted = abortController.signal.aborted;
|
|
348
395
|
const errorMsg = isAborted ? 'Connection timeout' : err instanceof Error ? err.message : 'Failed to fetch';
|
|
349
396
|
this._disconnectReason = isAborted ? 'timeout' : 'network_error';
|
|
@@ -355,27 +402,30 @@ export class FetchSseDriver {
|
|
|
355
402
|
type: 'error',
|
|
356
403
|
message: errorMsg
|
|
357
404
|
});
|
|
358
|
-
this._scheduleReconnect(true, undefined, attemptVersion);
|
|
405
|
+
this._scheduleReconnect(true, undefined, attemptVersion, config);
|
|
359
406
|
return;
|
|
360
407
|
}
|
|
361
|
-
|
|
362
|
-
|
|
408
|
+
if (connectionTimer !== undefined) {
|
|
409
|
+
clearTimeout(connectionTimer);
|
|
410
|
+
if (this._connectionTimer === connectionTimer) {
|
|
411
|
+
this._connectionTimer = undefined;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
if (this._isStale(attemptVersion)) return;
|
|
363
415
|
const statusCode = response.status;
|
|
364
416
|
this._lastStatusCode = statusCode;
|
|
365
417
|
let errorBody;
|
|
366
|
-
if (statusCode >= 400
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
} catch {
|
|
370
|
-
// Ignore body reading error
|
|
371
|
-
}
|
|
418
|
+
if (statusCode >= 400) {
|
|
419
|
+
errorBody = await this._readBoundedErrorBody(response, connectionTimeoutMs, requestStartTime, abortController, attemptVersion);
|
|
420
|
+
if (this._isStale(attemptVersion)) return;
|
|
372
421
|
}
|
|
373
422
|
|
|
374
423
|
// 3. HTTP Validation Rules matching Native (WHATWG SSE Section 9.1)
|
|
375
424
|
// 3a. HTTP 200 OK: Content-Type MIME type MUST be text/event-stream
|
|
376
425
|
if (statusCode === 200) {
|
|
377
426
|
const contentType = response.headers.get('Content-Type') ?? '';
|
|
378
|
-
const
|
|
427
|
+
const semiIdx = contentType.indexOf(';');
|
|
428
|
+
const mimeType = (semiIdx === -1 ? contentType : contentType.slice(0, semiIdx)).trim().toLowerCase();
|
|
379
429
|
if (mimeType !== 'text/event-stream') {
|
|
380
430
|
this._disconnectReason = 'server_error';
|
|
381
431
|
this._failAndStop(`Invalid Content-Type: expected text/event-stream but received '${contentType}'. Stopping.`, statusCode);
|
|
@@ -388,25 +438,28 @@ export class FetchSseDriver {
|
|
|
388
438
|
return;
|
|
389
439
|
} else if (statusCode === 401 || statusCode === 403) {
|
|
390
440
|
// 3c. HTTP 401/403 Auth errors
|
|
391
|
-
const maxAuthRetries =
|
|
441
|
+
const maxAuthRetries = config.maxAuthRetries ?? 3;
|
|
392
442
|
if (!this._onBeforeRequest) {
|
|
393
443
|
this._disconnectReason = 'server_error';
|
|
394
|
-
this._failAndStop(`Auth Error (${statusCode}) - No interceptor provided. Stopping.`, statusCode);
|
|
444
|
+
this._failAndStop(`Auth Error (${statusCode}) - No interceptor provided. Stopping.`, statusCode, errorBody);
|
|
395
445
|
return;
|
|
396
446
|
}
|
|
397
447
|
this._consecutiveAuthErrors++;
|
|
398
448
|
if (this._consecutiveAuthErrors > maxAuthRetries) {
|
|
399
449
|
this._disconnectReason = 'server_error';
|
|
400
|
-
this._failAndStop(`Auth Error (${statusCode}) - Retry limit reached (${maxAuthRetries}). Stopping.`, statusCode);
|
|
450
|
+
this._failAndStop(`Auth Error (${statusCode}) - Retry limit reached (${maxAuthRetries}). Stopping.`, statusCode, errorBody);
|
|
401
451
|
return;
|
|
402
452
|
}
|
|
403
453
|
this._recordError(`Auth Error (${statusCode})`, String(statusCode));
|
|
404
454
|
this._pushEvent({
|
|
405
455
|
type: 'error',
|
|
406
456
|
statusCode,
|
|
407
|
-
message: `Auth Error (${statusCode}) - Retry ${this._consecutiveAuthErrors}/${maxAuthRetries}. Refreshing token
|
|
457
|
+
message: `Auth Error (${statusCode}) - Retry ${this._consecutiveAuthErrors}/${maxAuthRetries}. Refreshing token...`,
|
|
458
|
+
...(errorBody !== undefined ? {
|
|
459
|
+
data: errorBody
|
|
460
|
+
} : {})
|
|
408
461
|
});
|
|
409
|
-
this._scheduleReconnect(true, undefined, attemptVersion);
|
|
462
|
+
this._scheduleReconnect(true, undefined, attemptVersion, config);
|
|
410
463
|
return;
|
|
411
464
|
} else if (statusCode === 408) {
|
|
412
465
|
// 3d. Request Timeout: Recoverable per WHATWG SSE and Native specs
|
|
@@ -416,9 +469,12 @@ export class FetchSseDriver {
|
|
|
416
469
|
this._pushEvent({
|
|
417
470
|
type: 'error',
|
|
418
471
|
statusCode: 408,
|
|
419
|
-
message: 'HTTP 408'
|
|
472
|
+
message: 'HTTP 408',
|
|
473
|
+
...(errorBody !== undefined ? {
|
|
474
|
+
data: errorBody
|
|
475
|
+
} : {})
|
|
420
476
|
});
|
|
421
|
-
this._scheduleReconnect(true, undefined, attemptVersion);
|
|
477
|
+
this._scheduleReconnect(true, undefined, attemptVersion, config);
|
|
422
478
|
return;
|
|
423
479
|
} else if (statusCode === 429 || statusCode === 503) {
|
|
424
480
|
// 3e. Rate limit / Service unavailable: Honor Retry-After
|
|
@@ -427,52 +483,66 @@ export class FetchSseDriver {
|
|
|
427
483
|
this._disconnectReason = 'server_error';
|
|
428
484
|
this._recordError(`HTTP ${statusCode}`, String(statusCode));
|
|
429
485
|
if (rawRetryAfterMs !== undefined) {
|
|
430
|
-
const maxIntervalMs =
|
|
486
|
+
const maxIntervalMs = config.maxRetryIntervalMs ?? 30000;
|
|
431
487
|
const boundedRetryMs = Math.max(0, Math.min(rawRetryAfterMs, maxIntervalMs));
|
|
488
|
+
const jitter = 500 + Math.floor(Math.random() * 1001); // 0.5s - 1.5s matching Native
|
|
489
|
+
const totalDelayMs = Math.max(1000, boundedRetryMs + jitter);
|
|
432
490
|
this._pushEvent({
|
|
433
491
|
type: 'error',
|
|
434
492
|
statusCode,
|
|
435
|
-
retry:
|
|
436
|
-
message: `Retry-After received: ${Math.round(
|
|
493
|
+
retry: totalDelayMs,
|
|
494
|
+
message: `Retry-After received: ${Math.round(totalDelayMs / 1000)}s`,
|
|
495
|
+
...(errorBody !== undefined ? {
|
|
496
|
+
data: errorBody
|
|
497
|
+
} : {})
|
|
437
498
|
});
|
|
438
|
-
this._scheduleReconnect(true,
|
|
499
|
+
this._scheduleReconnect(true, totalDelayMs, attemptVersion, config);
|
|
439
500
|
return;
|
|
440
501
|
}
|
|
441
502
|
if (statusCode === 429) {
|
|
442
503
|
this._pushEvent({
|
|
443
504
|
type: 'error',
|
|
444
505
|
statusCode: 429,
|
|
445
|
-
message: 'Rate Limited (429). Retrying with backoff...'
|
|
506
|
+
message: 'Rate Limited (429). Retrying with backoff...',
|
|
507
|
+
...(errorBody !== undefined ? {
|
|
508
|
+
data: errorBody
|
|
509
|
+
} : {})
|
|
446
510
|
});
|
|
447
|
-
this._scheduleReconnect(true, undefined, attemptVersion);
|
|
511
|
+
this._scheduleReconnect(true, undefined, attemptVersion, config);
|
|
448
512
|
return;
|
|
449
513
|
}
|
|
450
514
|
this._pushEvent({
|
|
451
515
|
type: 'error',
|
|
452
516
|
statusCode,
|
|
453
|
-
message: `HTTP ${statusCode}
|
|
517
|
+
message: `HTTP ${statusCode}`,
|
|
518
|
+
...(errorBody !== undefined ? {
|
|
519
|
+
data: errorBody
|
|
520
|
+
} : {})
|
|
454
521
|
});
|
|
455
|
-
this._scheduleReconnect(true, undefined, attemptVersion);
|
|
522
|
+
this._scheduleReconnect(true, undefined, attemptVersion, config);
|
|
456
523
|
return;
|
|
457
524
|
} else if (statusCode >= 400 && statusCode <= 499) {
|
|
458
525
|
// 3f. Fatal client error (e.g. 400 Bad Request, 404 Not Found, 405 Method Not Allowed)
|
|
459
526
|
this._disconnectReason = 'server_error';
|
|
460
|
-
const
|
|
461
|
-
const fatalMessage =
|
|
462
|
-
this._failAndStop(fatalMessage, statusCode);
|
|
527
|
+
const bodyPreview = formatErrorBodyPreview(errorBody);
|
|
528
|
+
const fatalMessage = bodyPreview ? `Fatal Error (${statusCode}): ${bodyPreview}` : `Fatal Error (${statusCode}). Stopping.`;
|
|
529
|
+
this._failAndStop(fatalMessage, statusCode, errorBody);
|
|
463
530
|
return;
|
|
464
531
|
} else if (statusCode >= 500) {
|
|
465
532
|
// 3g. Server error: Recoverable
|
|
466
533
|
this._disconnectReason = 'server_error';
|
|
467
534
|
this._recordError(`Server Error (${statusCode})`, String(statusCode));
|
|
468
|
-
const
|
|
469
|
-
const errorMsg =
|
|
535
|
+
const bodyPreview = formatErrorBodyPreview(errorBody);
|
|
536
|
+
const errorMsg = bodyPreview ? `Server Error (${statusCode}): ${bodyPreview}` : `Server Error (${statusCode})`;
|
|
470
537
|
this._pushEvent({
|
|
471
538
|
type: 'error',
|
|
472
539
|
statusCode,
|
|
473
|
-
message: errorMsg
|
|
540
|
+
message: errorMsg,
|
|
541
|
+
...(errorBody !== undefined ? {
|
|
542
|
+
data: errorBody
|
|
543
|
+
} : {})
|
|
474
544
|
});
|
|
475
|
-
this._scheduleReconnect(true, undefined, attemptVersion);
|
|
545
|
+
this._scheduleReconnect(true, undefined, attemptVersion, config);
|
|
476
546
|
return;
|
|
477
547
|
} else {
|
|
478
548
|
// Any other non-200 status code (e.g. 201 Created, 202, 3xx) is fatal per WHATWG SSE Section 9.1
|
|
@@ -488,75 +558,89 @@ export class FetchSseDriver {
|
|
|
488
558
|
// 4. Connection established successfully
|
|
489
559
|
this._reconnectStrategy.reset();
|
|
490
560
|
this._consecutiveAuthErrors = 0;
|
|
491
|
-
if (this._isReconnecting
|
|
561
|
+
if (this._isReconnecting) {
|
|
492
562
|
this._reconnectCount++;
|
|
493
563
|
this._isReconnecting = false;
|
|
494
564
|
}
|
|
495
565
|
this._connectedAt = Date.now();
|
|
496
566
|
this._updateState('open');
|
|
567
|
+
if (this._isStale(attemptVersion)) return;
|
|
497
568
|
this._pushEvent({
|
|
498
569
|
type: 'open',
|
|
499
570
|
statusCode
|
|
500
571
|
});
|
|
572
|
+
if (this._isStale(attemptVersion)) return;
|
|
501
573
|
|
|
502
574
|
// 5. Initialize streaming reader and parser
|
|
503
|
-
|
|
575
|
+
const parser = new SseEventParser(this, this._lastProcessedId);
|
|
576
|
+
this._activeParser = parser;
|
|
504
577
|
const reader = response.body.getReader();
|
|
505
578
|
this._activeReader = reader;
|
|
506
579
|
const decoder = new TextDecoder('utf-8');
|
|
507
580
|
|
|
508
581
|
// 6. Setup idle read timeout
|
|
509
|
-
this._resetReadTimeout(attemptVersion);
|
|
582
|
+
this._resetReadTimeout(attemptVersion, config);
|
|
510
583
|
try {
|
|
511
|
-
while (this.
|
|
584
|
+
while (!this._isStale(attemptVersion)) {
|
|
512
585
|
const {
|
|
513
586
|
value,
|
|
514
587
|
done
|
|
515
588
|
} = await reader.read();
|
|
589
|
+
if (this._isStale(attemptVersion)) {
|
|
590
|
+
break;
|
|
591
|
+
}
|
|
516
592
|
if (done) {
|
|
517
|
-
decoder.decode();
|
|
518
|
-
|
|
593
|
+
const tail = decoder.decode();
|
|
594
|
+
if (tail) {
|
|
595
|
+
parser.feed(tail);
|
|
596
|
+
}
|
|
597
|
+
parser.endOfStream();
|
|
519
598
|
break;
|
|
520
599
|
}
|
|
521
600
|
if (value) {
|
|
522
|
-
if (this._timeToFirstByteMs === undefined
|
|
523
|
-
this._timeToFirstByteMs = Date.now() -
|
|
601
|
+
if (this._timeToFirstByteMs === undefined) {
|
|
602
|
+
this._timeToFirstByteMs = Date.now() - attemptStartTime;
|
|
524
603
|
}
|
|
525
604
|
this._rawBytesReceived += value.byteLength;
|
|
526
605
|
this._chunksReceived++;
|
|
527
|
-
this._resetReadTimeout(attemptVersion);
|
|
606
|
+
this._resetReadTimeout(attemptVersion, config);
|
|
528
607
|
const text = decoder.decode(value, {
|
|
529
608
|
stream: true
|
|
530
609
|
});
|
|
531
|
-
|
|
610
|
+
parser.feed(text);
|
|
532
611
|
}
|
|
533
612
|
}
|
|
534
613
|
} catch (readErr) {
|
|
535
|
-
if (
|
|
614
|
+
if (this._isStale(attemptVersion)) return;
|
|
536
615
|
const isAborted = abortController.signal.aborted;
|
|
537
616
|
if (!isAborted) {
|
|
538
|
-
|
|
539
|
-
this.
|
|
617
|
+
const errorMsg = readErr instanceof Error ? readErr.message : 'Read error';
|
|
618
|
+
this._disconnectReason = 'network_error';
|
|
619
|
+
this._recordError(errorMsg, undefined);
|
|
620
|
+
this._pushEvent({
|
|
621
|
+
type: 'error',
|
|
622
|
+
message: errorMsg
|
|
623
|
+
});
|
|
624
|
+
this._scheduleReconnect(true, undefined, attemptVersion, config);
|
|
540
625
|
return;
|
|
541
626
|
}
|
|
542
627
|
} finally {
|
|
543
628
|
this._clearReadTimeout();
|
|
544
629
|
}
|
|
545
|
-
if (
|
|
630
|
+
if (this._isStale(attemptVersion)) return;
|
|
546
631
|
|
|
547
632
|
// Clean disconnect from server
|
|
548
|
-
this._scheduleReconnect(false, undefined, attemptVersion);
|
|
633
|
+
this._scheduleReconnect(false, undefined, attemptVersion, config);
|
|
549
634
|
}
|
|
550
635
|
|
|
551
636
|
// =========================================================================
|
|
552
637
|
// Reconnect & Teardown Helpers
|
|
553
638
|
// =========================================================================
|
|
554
639
|
|
|
555
|
-
_scheduleReconnect(isError, fixedDelayMs, attemptVersion) {
|
|
556
|
-
if (
|
|
640
|
+
_scheduleReconnect(isError, fixedDelayMs, attemptVersion, config) {
|
|
641
|
+
if (this._isStale(attemptVersion)) return;
|
|
557
642
|
if (this._reconnectStrategy.hasReachedMaxAttempts()) {
|
|
558
|
-
|
|
559
|
-
this._failAndStop(`Max reconnection attempts reached (${maxAttempts}).`);
|
|
643
|
+
this._failAndStop(`Max reconnection attempts reached (${this._reconnectStrategy.maxReconnectAttempts}).`);
|
|
560
644
|
return;
|
|
561
645
|
}
|
|
562
646
|
let delay;
|
|
@@ -573,8 +657,9 @@ export class FetchSseDriver {
|
|
|
573
657
|
this._updateState('reconnecting');
|
|
574
658
|
this._cleanupTransport();
|
|
575
659
|
this._reconnectTimer = setTimeout(() => {
|
|
576
|
-
|
|
577
|
-
|
|
660
|
+
this._reconnectTimer = undefined;
|
|
661
|
+
if (!this._isStale(newVersion)) {
|
|
662
|
+
this._establishConnection(newVersion, config);
|
|
578
663
|
}
|
|
579
664
|
}, delay);
|
|
580
665
|
}
|
|
@@ -582,27 +667,37 @@ export class FetchSseDriver {
|
|
|
582
667
|
this._connectedAt = undefined;
|
|
583
668
|
this._isRunning = false;
|
|
584
669
|
this._isReconnecting = false;
|
|
670
|
+
this._wasRunningBeforeNetworkLoss = false;
|
|
671
|
+
this._reconnectStrategy.reset();
|
|
585
672
|
this._connectionAttemptVersion++;
|
|
586
|
-
this.
|
|
587
|
-
this._cleanupTransport();
|
|
588
|
-
this._flushBatch();
|
|
673
|
+
this._teardownConnection();
|
|
589
674
|
if (emitClosed && this._state !== 'failed') {
|
|
590
675
|
this._updateState('closed');
|
|
591
|
-
this._flushBatch();
|
|
592
676
|
}
|
|
593
677
|
}
|
|
594
|
-
_failAndStop(message, statusCode) {
|
|
595
|
-
this._connectionAttemptVersion++;
|
|
678
|
+
_failAndStop(message, statusCode, data) {
|
|
596
679
|
this._recordError(message, statusCode !== undefined ? String(statusCode) : undefined);
|
|
597
680
|
this._pushEvent({
|
|
598
681
|
type: 'error',
|
|
599
682
|
message,
|
|
600
|
-
statusCode
|
|
683
|
+
statusCode,
|
|
684
|
+
...(data !== undefined ? {
|
|
685
|
+
data
|
|
686
|
+
} : {})
|
|
601
687
|
});
|
|
602
688
|
this._updateState('failed');
|
|
603
689
|
this._stopInternal(false);
|
|
604
690
|
}
|
|
691
|
+
_teardownConnection() {
|
|
692
|
+
this._cleanupTimers();
|
|
693
|
+
this._cleanupTransport();
|
|
694
|
+
this._flushBatch();
|
|
695
|
+
}
|
|
605
696
|
_cleanupTransport() {
|
|
697
|
+
if (this._activeParser) {
|
|
698
|
+
this._activeParser.abort();
|
|
699
|
+
this._activeParser = undefined;
|
|
700
|
+
}
|
|
606
701
|
if (this._activeReader) {
|
|
607
702
|
try {
|
|
608
703
|
this._activeReader.cancel().catch(() => {});
|
|
@@ -620,11 +715,150 @@ export class FetchSseDriver {
|
|
|
620
715
|
this._abortController = undefined;
|
|
621
716
|
}
|
|
622
717
|
}
|
|
718
|
+
async _readBoundedErrorBody(response, connectionTimeoutMs, requestStartTime, abortController, attemptVersion) {
|
|
719
|
+
const effectiveTimeoutMs = connectionTimeoutMs > 0 ? connectionTimeoutMs : 15000;
|
|
720
|
+
const remainingTimeoutMs = Math.max(0, effectiveTimeoutMs - (Date.now() - requestStartTime));
|
|
721
|
+
if (remainingTimeoutMs <= 0) {
|
|
722
|
+
try {
|
|
723
|
+
response.body?.cancel?.().catch(() => {});
|
|
724
|
+
} catch {
|
|
725
|
+
// Ignore cancellation errors
|
|
726
|
+
}
|
|
727
|
+
return undefined;
|
|
728
|
+
}
|
|
729
|
+
if (response.body && typeof response.body.getReader === 'function') {
|
|
730
|
+
const reader = response.body.getReader();
|
|
731
|
+
this._activeReader = reader;
|
|
732
|
+
const chunks = [];
|
|
733
|
+
let totalBytes = 0;
|
|
734
|
+
let timedOut = false;
|
|
735
|
+
let streamTimer;
|
|
736
|
+
const timeoutPromise = new Promise(resolve => {
|
|
737
|
+
streamTimer = setTimeout(() => {
|
|
738
|
+
if (this._errorBodyTimer === streamTimer) {
|
|
739
|
+
this._errorBodyTimer = undefined;
|
|
740
|
+
}
|
|
741
|
+
timedOut = true;
|
|
742
|
+
resolve({
|
|
743
|
+
value: undefined,
|
|
744
|
+
done: true
|
|
745
|
+
});
|
|
746
|
+
try {
|
|
747
|
+
reader.cancel().catch(() => {});
|
|
748
|
+
} catch {
|
|
749
|
+
// Ignore reader cancellation errors
|
|
750
|
+
}
|
|
751
|
+
try {
|
|
752
|
+
abortController.abort();
|
|
753
|
+
} catch {
|
|
754
|
+
// Ignore abort errors
|
|
755
|
+
}
|
|
756
|
+
}, remainingTimeoutMs);
|
|
757
|
+
this._errorBodyTimer = streamTimer;
|
|
758
|
+
});
|
|
759
|
+
try {
|
|
760
|
+
while (totalBytes < MAX_ERROR_BODY_BYTES && !timedOut && !this._isStale(attemptVersion)) {
|
|
761
|
+
const {
|
|
762
|
+
value,
|
|
763
|
+
done
|
|
764
|
+
} = await Promise.race([reader.read(), timeoutPromise]);
|
|
765
|
+
if (timedOut || this._isStale(attemptVersion) || done) {
|
|
766
|
+
break;
|
|
767
|
+
}
|
|
768
|
+
if (value && value.byteLength > 0) {
|
|
769
|
+
const remaining = MAX_ERROR_BODY_BYTES - totalBytes;
|
|
770
|
+
const slice = value.byteLength > remaining ? value.subarray(0, remaining) : value;
|
|
771
|
+
chunks.push(slice);
|
|
772
|
+
totalBytes += slice.byteLength;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
} catch {
|
|
776
|
+
// Preserve already-buffered partial error body bytes before disconnect/abort
|
|
777
|
+
} finally {
|
|
778
|
+
if (streamTimer !== undefined) {
|
|
779
|
+
clearTimeout(streamTimer);
|
|
780
|
+
if (this._errorBodyTimer === streamTimer) {
|
|
781
|
+
this._errorBodyTimer = undefined;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
if (this._activeReader === reader) {
|
|
785
|
+
this._activeReader = undefined;
|
|
786
|
+
}
|
|
787
|
+
try {
|
|
788
|
+
reader.cancel().catch(() => {});
|
|
789
|
+
} catch {
|
|
790
|
+
// Ignore reader cancellation errors
|
|
791
|
+
}
|
|
792
|
+
try {
|
|
793
|
+
reader.releaseLock();
|
|
794
|
+
} catch {
|
|
795
|
+
// Ignore releaseLock errors
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
if (this._isStale(attemptVersion) || totalBytes === 0) {
|
|
799
|
+
return undefined;
|
|
800
|
+
}
|
|
801
|
+
let combined;
|
|
802
|
+
if (chunks.length === 1 && chunks[0]) {
|
|
803
|
+
combined = chunks[0];
|
|
804
|
+
} else {
|
|
805
|
+
combined = new Uint8Array(totalBytes);
|
|
806
|
+
let offset = 0;
|
|
807
|
+
for (const chunk of chunks) {
|
|
808
|
+
combined.set(chunk, offset);
|
|
809
|
+
offset += chunk.byteLength;
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
const decoded = new TextDecoder('utf-8').decode(combined);
|
|
813
|
+
return decoded.length > 0 ? decoded : undefined;
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
// Fallback for environments without ReadableStream body support
|
|
817
|
+
let fallbackTimer;
|
|
818
|
+
const fallbackTimeoutPromise = new Promise(resolve => {
|
|
819
|
+
fallbackTimer = setTimeout(() => {
|
|
820
|
+
if (this._errorBodyTimer === fallbackTimer) {
|
|
821
|
+
this._errorBodyTimer = undefined;
|
|
822
|
+
}
|
|
823
|
+
resolve(undefined);
|
|
824
|
+
try {
|
|
825
|
+
abortController.abort();
|
|
826
|
+
} catch {
|
|
827
|
+
// Ignore abort errors
|
|
828
|
+
}
|
|
829
|
+
}, remainingTimeoutMs);
|
|
830
|
+
this._errorBodyTimer = fallbackTimer;
|
|
831
|
+
});
|
|
832
|
+
let raw;
|
|
833
|
+
try {
|
|
834
|
+
raw = await Promise.race([response.text(), fallbackTimeoutPromise]);
|
|
835
|
+
} catch {
|
|
836
|
+
// Ignore body reading error
|
|
837
|
+
} finally {
|
|
838
|
+
if (fallbackTimer !== undefined) {
|
|
839
|
+
clearTimeout(fallbackTimer);
|
|
840
|
+
if (this._errorBodyTimer === fallbackTimer) {
|
|
841
|
+
this._errorBodyTimer = undefined;
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
if (this._isStale(attemptVersion) || !raw) {
|
|
846
|
+
return undefined;
|
|
847
|
+
}
|
|
848
|
+
const encoded = new TextEncoder().encode(raw);
|
|
849
|
+
const bounded = encoded.byteLength > MAX_ERROR_BODY_BYTES ? encoded.subarray(0, MAX_ERROR_BODY_BYTES) : encoded;
|
|
850
|
+
const decoded = new TextDecoder('utf-8').decode(bounded);
|
|
851
|
+
return decoded.length > 0 ? decoded : undefined;
|
|
852
|
+
}
|
|
623
853
|
_cleanupTimers() {
|
|
624
854
|
if (this._connectionTimer) {
|
|
625
855
|
clearTimeout(this._connectionTimer);
|
|
626
856
|
this._connectionTimer = undefined;
|
|
627
857
|
}
|
|
858
|
+
if (this._errorBodyTimer) {
|
|
859
|
+
clearTimeout(this._errorBodyTimer);
|
|
860
|
+
this._errorBodyTimer = undefined;
|
|
861
|
+
}
|
|
628
862
|
if (this._readTimeoutTimer) {
|
|
629
863
|
clearTimeout(this._readTimeoutTimer);
|
|
630
864
|
this._readTimeoutTimer = undefined;
|
|
@@ -633,21 +867,23 @@ export class FetchSseDriver {
|
|
|
633
867
|
clearTimeout(this._reconnectTimer);
|
|
634
868
|
this._reconnectTimer = undefined;
|
|
635
869
|
}
|
|
636
|
-
if (this._batchTimer) {
|
|
637
|
-
clearTimeout(this._batchTimer);
|
|
638
|
-
this._batchTimer = undefined;
|
|
639
|
-
}
|
|
640
870
|
}
|
|
641
|
-
_resetReadTimeout(attemptVersion) {
|
|
871
|
+
_resetReadTimeout(attemptVersion, config = this._config) {
|
|
642
872
|
this._clearReadTimeout();
|
|
643
|
-
const readTimeoutMs =
|
|
873
|
+
const readTimeoutMs = config.readTimeoutMs ?? 300000;
|
|
644
874
|
if (readTimeoutMs <= 0) return;
|
|
645
875
|
this._readTimeoutTimer = setTimeout(() => {
|
|
646
|
-
|
|
876
|
+
this._readTimeoutTimer = undefined;
|
|
877
|
+
if (!this._isStale(attemptVersion)) {
|
|
647
878
|
this._disconnectReason = 'timeout';
|
|
648
879
|
this._updateState('stale');
|
|
649
|
-
|
|
650
|
-
this.
|
|
880
|
+
const errorMsg = 'Read timeout';
|
|
881
|
+
this._recordError(errorMsg, undefined);
|
|
882
|
+
this._pushEvent({
|
|
883
|
+
type: 'error',
|
|
884
|
+
message: errorMsg
|
|
885
|
+
});
|
|
886
|
+
this._scheduleReconnect(true, undefined, attemptVersion, config);
|
|
651
887
|
}
|
|
652
888
|
}, readTimeoutMs);
|
|
653
889
|
}
|
|
@@ -691,17 +927,15 @@ export class FetchSseDriver {
|
|
|
691
927
|
|
|
692
928
|
_pushEvent(event) {
|
|
693
929
|
const batchingIntervalMs = this._config?.batchingIntervalMs ?? 0;
|
|
694
|
-
const maxBufferSize = this._config?.maxBufferSize
|
|
930
|
+
const maxBufferSize = resolveMaxBufferSize(this._config?.maxBufferSize);
|
|
695
931
|
this._batchBuffer.push(event);
|
|
696
932
|
if (this._batchBuffer.length > this._peakBufferedEvents) {
|
|
697
933
|
this._peakBufferedEvents = this._batchBuffer.length;
|
|
698
934
|
}
|
|
699
|
-
if (
|
|
700
|
-
this._bufferOverflowCount++;
|
|
701
|
-
this._cancelBatchTimer();
|
|
935
|
+
if (batchingIntervalMs <= 0) {
|
|
702
936
|
this._flushBatch();
|
|
703
|
-
} else if (this._batchBuffer.length >= maxBufferSize
|
|
704
|
-
this.
|
|
937
|
+
} else if (this._batchBuffer.length >= maxBufferSize) {
|
|
938
|
+
this._bufferOverflowCount++;
|
|
705
939
|
this._flushBatch();
|
|
706
940
|
} else if (!this._batchTimer) {
|
|
707
941
|
this._batchTimer = setTimeout(() => {
|
|
@@ -724,37 +958,34 @@ export class FetchSseDriver {
|
|
|
724
958
|
this._batchTimer = undefined;
|
|
725
959
|
}
|
|
726
960
|
}
|
|
961
|
+
_recordActivity(now) {
|
|
962
|
+
if (this._lastActivityTime > 0) {
|
|
963
|
+
const gap = now - this._lastActivityTime;
|
|
964
|
+
if (gap > this._maxEventGapMs) {
|
|
965
|
+
this._maxEventGapMs = gap;
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
this._lastActivityTime = now;
|
|
969
|
+
}
|
|
727
970
|
|
|
728
971
|
// =========================================================================
|
|
729
972
|
// SseEventParserDelegate Implementation
|
|
730
973
|
// =========================================================================
|
|
731
974
|
|
|
732
975
|
onEvent(id, type, data) {
|
|
976
|
+
if (!this._isRunning) return;
|
|
733
977
|
const now = Date.now();
|
|
734
978
|
this._lastEventTime = now;
|
|
735
|
-
|
|
736
|
-
const gap = now - this._lastActivityTime;
|
|
737
|
-
if (gap > this._maxEventGapMs) {
|
|
738
|
-
this._maxEventGapMs = gap;
|
|
739
|
-
}
|
|
740
|
-
}
|
|
741
|
-
this._lastActivityTime = now;
|
|
979
|
+
this._recordActivity(now);
|
|
742
980
|
const eventType = type ?? 'message';
|
|
743
981
|
const encodedDataSize = getUtf8ByteCount(data);
|
|
744
982
|
const eventTypeSize = eventType === 'message' ? 0 : getUtf8ByteCount(eventType);
|
|
745
983
|
this._totalBytesReceived += encodedDataSize + eventTypeSize;
|
|
746
|
-
if (id !== undefined && id !== this._lastProcessedId) {
|
|
747
|
-
this._totalBytesReceived += getUtf8ByteCount(id);
|
|
748
|
-
this._lastProcessedId = id;
|
|
749
|
-
}
|
|
750
984
|
this._totalEventsReceived++;
|
|
751
985
|
let parsedData;
|
|
752
|
-
if (this._config?.autoParseJSON && data
|
|
986
|
+
if (this._config?.autoParseJSON && /^\s*\{/.test(data)) {
|
|
753
987
|
try {
|
|
754
|
-
|
|
755
|
-
if (obj && typeof obj === 'object' && !Array.isArray(obj)) {
|
|
756
|
-
parsedData = obj;
|
|
757
|
-
}
|
|
988
|
+
parsedData = JSON.parse(data);
|
|
758
989
|
} catch {
|
|
759
990
|
// Ignore JSON parsing failures
|
|
760
991
|
}
|
|
@@ -769,15 +1000,10 @@ export class FetchSseDriver {
|
|
|
769
1000
|
});
|
|
770
1001
|
}
|
|
771
1002
|
onComment(comment) {
|
|
1003
|
+
if (!this._isRunning) return;
|
|
772
1004
|
const now = Date.now();
|
|
773
1005
|
this._lastHeartbeatTime = now;
|
|
774
|
-
|
|
775
|
-
const gap = now - this._lastActivityTime;
|
|
776
|
-
if (gap > this._maxEventGapMs) {
|
|
777
|
-
this._maxEventGapMs = gap;
|
|
778
|
-
}
|
|
779
|
-
}
|
|
780
|
-
this._lastActivityTime = now;
|
|
1006
|
+
this._recordActivity(now);
|
|
781
1007
|
this._totalBytesReceived += getUtf8ByteCount(comment);
|
|
782
1008
|
this._commentsReceived++;
|
|
783
1009
|
this._pushEvent({
|
|
@@ -786,21 +1012,25 @@ export class FetchSseDriver {
|
|
|
786
1012
|
});
|
|
787
1013
|
}
|
|
788
1014
|
onRetry(retryMs) {
|
|
1015
|
+
if (!this._isRunning) return;
|
|
789
1016
|
this._serverRetryDelayMs = retryMs;
|
|
790
1017
|
this._reconnectStrategy.updateRetryInterval(retryMs);
|
|
791
1018
|
}
|
|
792
1019
|
onIdUpdate(id) {
|
|
1020
|
+
if (!this._isRunning) return;
|
|
793
1021
|
if (id !== undefined && id !== this._lastProcessedId) {
|
|
794
1022
|
this._totalBytesReceived += getUtf8ByteCount(id);
|
|
795
1023
|
}
|
|
796
1024
|
this._lastProcessedId = id;
|
|
797
1025
|
}
|
|
798
1026
|
onParseError(error) {
|
|
1027
|
+
if (!this._isRunning) return;
|
|
799
1028
|
this._parseErrors++;
|
|
800
1029
|
this._disconnectReason = 'parser_error';
|
|
801
1030
|
this._failAndStop(`SSE parser error: ${error.message}`);
|
|
802
1031
|
}
|
|
803
1032
|
onLinesParsed(count) {
|
|
1033
|
+
if (!this._isRunning) return;
|
|
804
1034
|
this._linesParsed += count;
|
|
805
1035
|
}
|
|
806
1036
|
|
|
@@ -809,37 +1039,35 @@ export class FetchSseDriver {
|
|
|
809
1039
|
// =========================================================================
|
|
810
1040
|
|
|
811
1041
|
_setupNetworkListeners() {
|
|
812
|
-
if (typeof window === 'undefined' || typeof window.addEventListener !== 'function' || this.
|
|
813
|
-
|
|
1042
|
+
if (typeof window === 'undefined' || typeof window.addEventListener !== 'function' || this._removeNetworkListeners !== undefined) return;
|
|
1043
|
+
const offlineListener = () => {
|
|
814
1044
|
if (this._isRunning) {
|
|
815
1045
|
this._wasRunningBeforeNetworkLoss = true;
|
|
816
1046
|
this._disconnectReason = 'network_error';
|
|
817
1047
|
this._connectionAttemptVersion++;
|
|
818
|
-
this.
|
|
819
|
-
this._cleanupTransport();
|
|
1048
|
+
this._teardownConnection();
|
|
820
1049
|
this._updateState('paused');
|
|
821
1050
|
this._isRunning = false;
|
|
822
1051
|
}
|
|
823
1052
|
};
|
|
824
|
-
|
|
1053
|
+
const onlineListener = () => {
|
|
825
1054
|
if (this._wasRunningBeforeNetworkLoss) {
|
|
826
1055
|
this._wasRunningBeforeNetworkLoss = false;
|
|
827
1056
|
this.start();
|
|
828
1057
|
}
|
|
829
1058
|
};
|
|
830
|
-
window
|
|
831
|
-
|
|
1059
|
+
const target = window;
|
|
1060
|
+
target.addEventListener('offline', offlineListener);
|
|
1061
|
+
target.addEventListener('online', onlineListener);
|
|
1062
|
+
this._removeNetworkListeners = () => {
|
|
1063
|
+
target.removeEventListener('offline', offlineListener);
|
|
1064
|
+
target.removeEventListener('online', onlineListener);
|
|
1065
|
+
};
|
|
832
1066
|
}
|
|
833
1067
|
_teardownNetworkListeners() {
|
|
834
|
-
if (typeof window === 'undefined' || typeof window.removeEventListener !== 'function') return;
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
this._offlineListener = undefined;
|
|
838
|
-
}
|
|
839
|
-
if (this._onlineListener) {
|
|
840
|
-
window.removeEventListener('online', this._onlineListener);
|
|
841
|
-
this._onlineListener = undefined;
|
|
842
|
-
}
|
|
1068
|
+
if (typeof window === 'undefined' || typeof window.removeEventListener !== 'function' || !this._removeNetworkListeners) return;
|
|
1069
|
+
this._removeNetworkListeners();
|
|
1070
|
+
this._removeNetworkListeners = undefined;
|
|
843
1071
|
}
|
|
844
1072
|
}
|
|
845
1073
|
//# sourceMappingURL=FetchSseDriver.js.map
|