@metarouter/react-native-sdk 1.5.0 → 1.7.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 +59 -10
- package/android/build.gradle +41 -0
- package/android/src/main/AndroidManifest.xml +4 -0
- package/android/src/main/java/com/metarouter/reactnative/MetaRouterNetworkMonitorModule.kt +119 -0
- package/android/src/main/java/com/metarouter/reactnative/MetaRouterPackage.kt +23 -0
- package/android/src/main/java/com/metarouter/reactnative/MetaRouterQueueStorageModule.kt +124 -0
- package/ios/MetaRouterNetworkMonitor.m +76 -0
- package/ios/MetaRouterQueueStorage.m +127 -0
- package/lib/analytics/MetaRouterAnalyticsClient.d.ts +23 -4
- package/lib/analytics/MetaRouterAnalyticsClient.d.ts.map +1 -1
- package/lib/analytics/MetaRouterAnalyticsClient.js +178 -89
- package/lib/analytics/dispatcher.d.ts +61 -4
- package/lib/analytics/dispatcher.d.ts.map +1 -1
- package/lib/analytics/dispatcher.js +248 -45
- package/lib/analytics/init.d.ts +1 -1
- package/lib/analytics/init.d.ts.map +1 -1
- package/lib/analytics/init.js +12 -2
- package/lib/analytics/persistence/NativeQueueStorage.d.ts +5 -0
- package/lib/analytics/persistence/NativeQueueStorage.d.ts.map +1 -0
- package/lib/analytics/persistence/NativeQueueStorage.js +59 -0
- package/lib/analytics/persistence/PersistentEventQueue.d.ts +96 -0
- package/lib/analytics/persistence/PersistentEventQueue.d.ts.map +1 -0
- package/lib/analytics/persistence/PersistentEventQueue.js +401 -0
- package/lib/analytics/persistence/types.d.ts +20 -0
- package/lib/analytics/persistence/types.d.ts.map +1 -0
- package/lib/analytics/persistence/types.js +10 -0
- package/lib/analytics/proxy/proxyClient.d.ts +1 -1
- package/lib/analytics/proxy/proxyClient.d.ts.map +1 -1
- package/lib/analytics/proxy/proxyClient.js +23 -29
- package/lib/analytics/types.d.ts +12 -4
- package/lib/analytics/types.d.ts.map +1 -1
- package/lib/analytics/utils/circuitBreaker.d.ts +4 -1
- package/lib/analytics/utils/circuitBreaker.d.ts.map +1 -1
- package/lib/analytics/utils/circuitBreaker.js +23 -14
- package/lib/analytics/utils/contextInfo.d.ts +1 -1
- package/lib/analytics/utils/contextInfo.d.ts.map +1 -1
- package/lib/analytics/utils/contextInfo.js +28 -24
- package/lib/analytics/utils/debouncedNetworkMonitor.d.ts +25 -0
- package/lib/analytics/utils/debouncedNetworkMonitor.d.ts.map +1 -0
- package/lib/analytics/utils/debouncedNetworkMonitor.js +68 -0
- package/lib/analytics/utils/networkMonitor.d.ts +30 -0
- package/lib/analytics/utils/networkMonitor.d.ts.map +1 -0
- package/lib/analytics/utils/networkMonitor.js +90 -0
- package/lib/analytics/utils/responseCategory.d.ts +14 -0
- package/lib/analytics/utils/responseCategory.d.ts.map +1 -0
- package/lib/analytics/utils/responseCategory.js +26 -0
- package/metarouter-react-native-sdk.podspec +19 -0
- package/package.json +27 -10
- package/react-native.config.js +15 -0
|
@@ -1,11 +1,24 @@
|
|
|
1
|
-
import type { EventPayload } from
|
|
2
|
-
import type CircuitBreaker from
|
|
3
|
-
export type CircuitState =
|
|
1
|
+
import type { EventPayload } from './types';
|
|
2
|
+
import type CircuitBreaker from './utils/circuitBreaker';
|
|
3
|
+
export type CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
|
|
4
|
+
export interface NetworkResponse {
|
|
5
|
+
statusCode: number;
|
|
6
|
+
}
|
|
4
7
|
export interface DispatcherOptions {
|
|
5
|
-
|
|
8
|
+
maxEventCount: number;
|
|
9
|
+
maxQueueBytes: number;
|
|
6
10
|
autoFlushThreshold: number;
|
|
7
11
|
maxBatchSize: number;
|
|
8
12
|
flushIntervalSeconds: number;
|
|
13
|
+
baseRetryDelayMs: number;
|
|
14
|
+
maxRetryDelayMs: number;
|
|
15
|
+
/**
|
|
16
|
+
* Whether disk persistence is enabled. When false, capacity overflow drops
|
|
17
|
+
* the oldest event (ring buffer) instead of splicing the whole queue to
|
|
18
|
+
* the onCapacityOverflow handler, since there is no disk to spill to.
|
|
19
|
+
*/
|
|
20
|
+
isPersistenceEnabled: () => boolean;
|
|
21
|
+
isNetworkAvailable: () => boolean;
|
|
9
22
|
endpoint: (path: string) => string;
|
|
10
23
|
fetchWithTimeout: (url: string, init: RequestInit, timeoutMs: number) => Promise<Response>;
|
|
11
24
|
canSend: () => boolean;
|
|
@@ -15,6 +28,9 @@ export interface DispatcherOptions {
|
|
|
15
28
|
log: (...args: any[]) => void;
|
|
16
29
|
warn: (...args: any[]) => void;
|
|
17
30
|
error: (...args: any[]) => void;
|
|
31
|
+
onCapacityOverflow?: (events: EventPayload[]) => void | Promise<void>;
|
|
32
|
+
onFlushToDisk?: (events: EventPayload[]) => void | Promise<void>;
|
|
33
|
+
onFlushComplete?: () => void;
|
|
18
34
|
onScheduleFlushIn?: (ms: number) => void;
|
|
19
35
|
onFatalConfig?: () => void;
|
|
20
36
|
}
|
|
@@ -26,18 +42,57 @@ export default class Dispatcher {
|
|
|
26
42
|
private nextScheduledAt;
|
|
27
43
|
private flushInFlight;
|
|
28
44
|
private maxBatchSize;
|
|
45
|
+
private readonly initialMaxBatchSize;
|
|
29
46
|
private circuit;
|
|
47
|
+
private queueSizeBytes;
|
|
48
|
+
private consecutiveRetries;
|
|
30
49
|
constructor(opts: DispatcherOptions);
|
|
31
50
|
getQueueRef(): EventPayload[];
|
|
51
|
+
/**
|
|
52
|
+
* Drain the in-memory queue entirely. Returns all events and resets the
|
|
53
|
+
* byte counter. Used by PersistentEventQueue to persist memory to disk
|
|
54
|
+
* without leaving duplicates behind.
|
|
55
|
+
*/
|
|
56
|
+
drainQueue(): EventPayload[];
|
|
57
|
+
/**
|
|
58
|
+
* Restore events to the front without applying capacity overflow policy.
|
|
59
|
+
* Used only after a failed durability handoff so events are not lost.
|
|
60
|
+
*/
|
|
61
|
+
restoreQueueFront(events: EventPayload[]): void;
|
|
32
62
|
start(): void;
|
|
33
63
|
stop(): void;
|
|
34
64
|
reset(): void;
|
|
65
|
+
/**
|
|
66
|
+
* Retry floor: exponential backoff independent of circuit breaker.
|
|
67
|
+
* Applies from the very first failure so retries aren't immediate while circuit is closed.
|
|
68
|
+
*/
|
|
69
|
+
private retryFloorMs;
|
|
35
70
|
private clearNextTimer;
|
|
36
71
|
scheduleFlushIn(ms: number): void;
|
|
72
|
+
private static encoder;
|
|
73
|
+
private estimateEventSize;
|
|
74
|
+
private handleCapacityOverflow;
|
|
75
|
+
private isOverCap;
|
|
37
76
|
enqueue(event: EventPayload): void;
|
|
77
|
+
enqueueFront(events: EventPayload[]): void;
|
|
78
|
+
getQueueSizeBytes(): number;
|
|
38
79
|
private drainBatch;
|
|
80
|
+
private requeueChunk;
|
|
39
81
|
private parseRetryAfter;
|
|
40
82
|
flush(): Promise<void>;
|
|
83
|
+
resetCircuitBreaker(): void;
|
|
84
|
+
/**
|
|
85
|
+
* Coordinate shutdown on a fatal config error (401/403/404).
|
|
86
|
+
* Called by the main flush path and by the disk drain so both paths
|
|
87
|
+
* converge to the same "disable client" signal.
|
|
88
|
+
*/
|
|
89
|
+
handleFatalConfig(statusCode: number): void;
|
|
90
|
+
/**
|
|
91
|
+
* Send a batch directly to network, bypassing the memory queue.
|
|
92
|
+
* Used by the disk drain to send events without loading them into the queue.
|
|
93
|
+
* Returns { statusCode } on HTTP response, null on network/transport error.
|
|
94
|
+
*/
|
|
95
|
+
sendBatchDirect(events: EventPayload[]): Promise<NetworkResponse | null>;
|
|
41
96
|
getDebugInfo(): {
|
|
42
97
|
queueLength: number;
|
|
43
98
|
flushIntervalSeconds: number;
|
|
@@ -47,6 +102,8 @@ export default class Dispatcher {
|
|
|
47
102
|
circuitRemainingMs: number;
|
|
48
103
|
maxQueueEvents: number;
|
|
49
104
|
maxBatchSize: number;
|
|
105
|
+
consecutiveRetries: number;
|
|
106
|
+
isNetworkAvailable: boolean;
|
|
50
107
|
};
|
|
51
108
|
}
|
|
52
109
|
//# sourceMappingURL=dispatcher.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dispatcher.d.ts","sourceRoot":"","sources":["../../src/analytics/dispatcher.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,cAAc,MAAM,wBAAwB,CAAC;AAEzD,MAAM,MAAM,YAAY,GAAG,QAAQ,GAAG,MAAM,GAAG,WAAW,CAAC;AAE3D,MAAM,WAAW,iBAAiB;IAChC,
|
|
1
|
+
{"version":3,"file":"dispatcher.d.ts","sourceRoot":"","sources":["../../src/analytics/dispatcher.ts"],"names":[],"mappings":"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"}
|
|
@@ -1,17 +1,37 @@
|
|
|
1
|
-
|
|
1
|
+
class Dispatcher {
|
|
2
2
|
constructor(opts) {
|
|
3
3
|
this.queue = [];
|
|
4
4
|
this.flushTimer = null;
|
|
5
5
|
this.nextTimer = null;
|
|
6
6
|
this.nextScheduledAt = null;
|
|
7
7
|
this.flushInFlight = null;
|
|
8
|
+
this.queueSizeBytes = 0;
|
|
9
|
+
this.consecutiveRetries = 0;
|
|
8
10
|
this.opts = opts;
|
|
9
|
-
this.
|
|
11
|
+
this.initialMaxBatchSize = Math.max(1, opts.maxBatchSize);
|
|
12
|
+
this.maxBatchSize = this.initialMaxBatchSize;
|
|
10
13
|
this.circuit = opts.createBreaker();
|
|
11
14
|
}
|
|
12
15
|
getQueueRef() {
|
|
13
16
|
return this.queue;
|
|
14
17
|
}
|
|
18
|
+
/**
|
|
19
|
+
* Drain the in-memory queue entirely. Returns all events and resets the
|
|
20
|
+
* byte counter. Used by PersistentEventQueue to persist memory to disk
|
|
21
|
+
* without leaving duplicates behind.
|
|
22
|
+
*/
|
|
23
|
+
drainQueue() {
|
|
24
|
+
const events = this.queue.splice(0);
|
|
25
|
+
this.queueSizeBytes = 0;
|
|
26
|
+
return events;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Restore events to the front without applying capacity overflow policy.
|
|
30
|
+
* Used only after a failed durability handoff so events are not lost.
|
|
31
|
+
*/
|
|
32
|
+
restoreQueueFront(events) {
|
|
33
|
+
this.requeueChunk(events);
|
|
34
|
+
}
|
|
15
35
|
start() {
|
|
16
36
|
if (this.flushTimer)
|
|
17
37
|
clearInterval(this.flushTimer);
|
|
@@ -27,8 +47,20 @@ export default class Dispatcher {
|
|
|
27
47
|
reset() {
|
|
28
48
|
this.stop();
|
|
29
49
|
this.queue.length = 0;
|
|
50
|
+
this.queueSizeBytes = 0;
|
|
51
|
+
this.consecutiveRetries = 0;
|
|
30
52
|
this.circuit = this.opts.createBreaker();
|
|
31
|
-
this.maxBatchSize =
|
|
53
|
+
this.maxBatchSize = this.initialMaxBatchSize;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Retry floor: exponential backoff independent of circuit breaker.
|
|
57
|
+
* Applies from the very first failure so retries aren't immediate while circuit is closed.
|
|
58
|
+
*/
|
|
59
|
+
retryFloorMs() {
|
|
60
|
+
if (this.consecutiveRetries <= 0)
|
|
61
|
+
return 0;
|
|
62
|
+
const exponent = Math.min(this.consecutiveRetries - 1, 10);
|
|
63
|
+
return Math.min(this.opts.maxRetryDelayMs, this.opts.baseRetryDelayMs * Math.pow(2, exponent));
|
|
32
64
|
}
|
|
33
65
|
clearNextTimer() {
|
|
34
66
|
if (this.nextTimer) {
|
|
@@ -52,31 +84,119 @@ export default class Dispatcher {
|
|
|
52
84
|
this.flush();
|
|
53
85
|
}, Math.max(0, ms));
|
|
54
86
|
}
|
|
87
|
+
estimateEventSize(event) {
|
|
88
|
+
return Dispatcher.encoder.encode(JSON.stringify(event)).byteLength;
|
|
89
|
+
}
|
|
90
|
+
handleCapacityOverflow(triggerDesc) {
|
|
91
|
+
// Persistence disabled (maxDiskEvents === 0): ring-buffer — drop oldest
|
|
92
|
+
// event one at a time instead of draining the whole queue, since there
|
|
93
|
+
// is no disk to spill to.
|
|
94
|
+
if (!this.opts.isPersistenceEnabled()) {
|
|
95
|
+
const dropped = this.queue.shift();
|
|
96
|
+
if (dropped !== undefined) {
|
|
97
|
+
this.queueSizeBytes -= this.estimateEventSize(dropped);
|
|
98
|
+
if (this.queueSizeBytes < 0)
|
|
99
|
+
this.queueSizeBytes = 0;
|
|
100
|
+
this.opts.warn(`Queue cap reached (${triggerDesc}) — dropped oldest event`);
|
|
101
|
+
}
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
// Persistence enabled: splice the whole queue to the disk handler.
|
|
105
|
+
if (this.opts.onCapacityOverflow) {
|
|
106
|
+
const flushed = this.queue.splice(0);
|
|
107
|
+
this.queueSizeBytes = 0;
|
|
108
|
+
try {
|
|
109
|
+
const result = this.opts.onCapacityOverflow(flushed);
|
|
110
|
+
void Promise.resolve(result).catch((err) => {
|
|
111
|
+
this.requeueChunk(flushed);
|
|
112
|
+
this.opts.warn('Capacity overflow persistence failed — restored events to memory', err);
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
catch (err) {
|
|
116
|
+
this.requeueChunk(flushed);
|
|
117
|
+
this.opts.warn('Capacity overflow persistence failed — restored events to memory', err);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
this.opts.warn(`Queue cap reached — dropping ${this.queue.length} event(s) (no overflow handler)`);
|
|
122
|
+
this.queue.length = 0;
|
|
123
|
+
this.queueSizeBytes = 0;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
isOverCap(extraBytes = 0, extraCount = 0) {
|
|
127
|
+
return (this.queue.length + extraCount > this.opts.maxEventCount ||
|
|
128
|
+
this.queueSizeBytes + extraBytes > this.opts.maxQueueBytes);
|
|
129
|
+
}
|
|
55
130
|
enqueue(event) {
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
131
|
+
const eventSize = this.estimateEventSize(event);
|
|
132
|
+
// Enforce cap: if adding this event would exceed count OR byte limit,
|
|
133
|
+
// flush/evict first so the new event still fits.
|
|
134
|
+
while (this.queue.length > 0 && this.isOverCap(eventSize, 1)) {
|
|
135
|
+
this.handleCapacityOverflow(this.queueSizeBytes + eventSize > this.opts.maxQueueBytes
|
|
136
|
+
? 'bytes'
|
|
137
|
+
: 'count');
|
|
138
|
+
if (!this.opts.isPersistenceEnabled() && this.queue.length === 0)
|
|
139
|
+
break;
|
|
140
|
+
// When persistence IS enabled, handleCapacityOverflow drains the whole
|
|
141
|
+
// queue so the loop exits naturally.
|
|
142
|
+
if (this.opts.isPersistenceEnabled())
|
|
143
|
+
break;
|
|
60
144
|
}
|
|
61
|
-
this.opts.log(
|
|
62
|
-
type: event === null || event === void 0 ? void 0 : event.type,
|
|
63
|
-
messageId: event === null || event === void 0 ? void 0 : event.messageId,
|
|
64
|
-
});
|
|
145
|
+
this.opts.log(`Enqueuing event {"messageId": "${event === null || event === void 0 ? void 0 : event.messageId}", "type": "${event === null || event === void 0 ? void 0 : event.type}"}`);
|
|
65
146
|
this.queue.push(event);
|
|
147
|
+
this.queueSizeBytes += eventSize;
|
|
148
|
+
this.opts.log(`Event enqueued, queue length: ${this.queue.length}`);
|
|
66
149
|
if (this.queue.length >= this.opts.autoFlushThreshold) {
|
|
67
|
-
this.opts.log(`Event queue reached ${this.opts.autoFlushThreshold}. Flushing queued events.`);
|
|
68
150
|
void this.flush();
|
|
69
151
|
}
|
|
70
152
|
}
|
|
153
|
+
enqueueFront(events) {
|
|
154
|
+
// Avoid spread into unshift — large arrays can exceed JS engine argument limit
|
|
155
|
+
const merged = events.concat(this.queue);
|
|
156
|
+
this.queue.length = 0;
|
|
157
|
+
for (let i = 0; i < merged.length; i++) {
|
|
158
|
+
this.queue.push(merged[i]);
|
|
159
|
+
}
|
|
160
|
+
for (const e of events) {
|
|
161
|
+
this.queueSizeBytes += this.estimateEventSize(e);
|
|
162
|
+
}
|
|
163
|
+
// Enforce cap: drain to disk (or ring-buffer drop-oldest in 0-mode).
|
|
164
|
+
while (this.isOverCap()) {
|
|
165
|
+
const before = this.queue.length;
|
|
166
|
+
this.handleCapacityOverflow(this.queueSizeBytes > this.opts.maxQueueBytes ? 'bytes' : 'count');
|
|
167
|
+
if (this.queue.length === before)
|
|
168
|
+
break; // safety: avoid infinite loop
|
|
169
|
+
if (this.opts.isPersistenceEnabled())
|
|
170
|
+
break; // drained entire queue
|
|
171
|
+
}
|
|
172
|
+
if (this.queue.length >= this.opts.autoFlushThreshold) {
|
|
173
|
+
void this.flush();
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
getQueueSizeBytes() {
|
|
177
|
+
return this.queueSizeBytes;
|
|
178
|
+
}
|
|
71
179
|
drainBatch() {
|
|
72
180
|
const n = Math.min(this.queue.length, this.maxBatchSize);
|
|
73
181
|
const nowIso = new Date().toISOString();
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
182
|
+
const drained = this.queue.splice(0, n);
|
|
183
|
+
const batch = drained.map((e) => {
|
|
184
|
+
this.queueSizeBytes -= this.estimateEventSize(e);
|
|
185
|
+
return { ...e, sentAt: nowIso };
|
|
186
|
+
});
|
|
78
187
|
return batch;
|
|
79
188
|
}
|
|
189
|
+
requeueChunk(chunk) {
|
|
190
|
+
// Avoid spread into unshift — large arrays can exceed JS engine argument limit
|
|
191
|
+
const merged = chunk.concat(this.queue);
|
|
192
|
+
this.queue.length = 0;
|
|
193
|
+
for (let i = 0; i < merged.length; i++) {
|
|
194
|
+
this.queue.push(merged[i]);
|
|
195
|
+
}
|
|
196
|
+
for (const e of chunk) {
|
|
197
|
+
this.queueSizeBytes += this.estimateEventSize(e);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
80
200
|
parseRetryAfter(h) {
|
|
81
201
|
if (!h)
|
|
82
202
|
return null;
|
|
@@ -91,29 +211,51 @@ export default class Dispatcher {
|
|
|
91
211
|
return;
|
|
92
212
|
if (this.flushInFlight)
|
|
93
213
|
return this.flushInFlight;
|
|
214
|
+
// A retry is armed — let it fire on its own schedule instead of
|
|
215
|
+
// launching immediately and bypassing the backoff window. The scheduled
|
|
216
|
+
// callback nils nextTimer before calling flush(), so it passes through.
|
|
217
|
+
if (this.nextTimer)
|
|
218
|
+
return;
|
|
94
219
|
if (!this.opts.canSend())
|
|
95
220
|
return;
|
|
96
221
|
const doFlush = async () => {
|
|
97
222
|
var _a, _b, _c, _d;
|
|
98
223
|
while (this.queue.length) {
|
|
224
|
+
if (!this.opts.isNetworkAvailable()) {
|
|
225
|
+
if (this.opts.onFlushToDisk && this.opts.isPersistenceEnabled()) {
|
|
226
|
+
const flushed = this.drainQueue();
|
|
227
|
+
try {
|
|
228
|
+
await this.opts.onFlushToDisk(flushed);
|
|
229
|
+
this.opts.warn(`Offline — flushed ${flushed.length} event(s) to disk`);
|
|
230
|
+
}
|
|
231
|
+
catch (err) {
|
|
232
|
+
this.requeueChunk(flushed);
|
|
233
|
+
this.opts.warn(`Offline — failed to flush ${flushed.length} event(s) to disk; restored to memory`, err);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
else {
|
|
237
|
+
this.opts.warn(`Offline — pausing HTTP attempts, ${this.queue.length} event(s) queued`);
|
|
238
|
+
}
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
99
241
|
if (!this.circuit.allowRequest()) {
|
|
100
242
|
const state = this.circuit.getState();
|
|
101
243
|
const wait = this.circuit.remainingCooldownMs();
|
|
102
|
-
this.opts.
|
|
244
|
+
this.opts.warn(`Circuit breaker ${state}, retrying in ${wait}ms (${this.queue.length} event(s) pending)`);
|
|
103
245
|
this.scheduleFlushIn(wait);
|
|
104
246
|
return;
|
|
105
247
|
}
|
|
106
248
|
const chunk = this.drainBatch();
|
|
107
249
|
try {
|
|
108
|
-
this.opts.log(
|
|
250
|
+
this.opts.log(`Making API call to: ${this.opts.endpoint('/v1/batch')}`);
|
|
109
251
|
const headers = {
|
|
110
|
-
|
|
252
|
+
'Content-Type': 'application/json',
|
|
111
253
|
};
|
|
112
254
|
if (this.opts.isTracingEnabled()) {
|
|
113
|
-
headers
|
|
255
|
+
headers.Trace = 'true';
|
|
114
256
|
}
|
|
115
|
-
const res = await this.opts.fetchWithTimeout(this.opts.endpoint(
|
|
116
|
-
method:
|
|
257
|
+
const res = await this.opts.fetchWithTimeout(this.opts.endpoint('/v1/batch'), {
|
|
258
|
+
method: 'POST',
|
|
117
259
|
headers,
|
|
118
260
|
body: JSON.stringify({ batch: chunk }),
|
|
119
261
|
}, 8000);
|
|
@@ -122,38 +264,37 @@ export default class Dispatcher {
|
|
|
122
264
|
// Retryable
|
|
123
265
|
if (s >= 500 || s === 408) {
|
|
124
266
|
this.circuit.onFailure();
|
|
267
|
+
this.consecutiveRetries += 1;
|
|
125
268
|
if (this.opts.isOperational()) {
|
|
126
|
-
this.
|
|
127
|
-
const retryAfter = (_a = this.parseRetryAfter(res.headers.get(
|
|
128
|
-
const wait = Math.max(this.circuit.remainingCooldownMs(), retryAfter, 1000);
|
|
129
|
-
this.opts.warn(`
|
|
269
|
+
this.requeueChunk(chunk);
|
|
270
|
+
const retryAfter = (_a = this.parseRetryAfter(res.headers.get('retry-after'))) !== null && _a !== void 0 ? _a : 0;
|
|
271
|
+
const wait = Math.max(this.retryFloorMs(), this.circuit.remainingCooldownMs(), retryAfter, 1000);
|
|
272
|
+
this.opts.warn(`Server error ${s}, will retry ${chunk.length} event(s) in ${wait}ms (circuit: ${this.circuit.getState()}, retry #${this.consecutiveRetries})`);
|
|
130
273
|
this.scheduleFlushIn(wait);
|
|
131
274
|
}
|
|
132
275
|
else {
|
|
133
|
-
this.opts.warn(
|
|
276
|
+
this.opts.warn('Flush aborted during reset/disable — dropping current chunk');
|
|
134
277
|
}
|
|
135
278
|
return;
|
|
136
279
|
}
|
|
137
280
|
if (s === 429) {
|
|
138
281
|
this.circuit.onFailure();
|
|
282
|
+
this.consecutiveRetries += 1;
|
|
139
283
|
if (this.opts.isOperational()) {
|
|
140
|
-
this.
|
|
141
|
-
const h = (_b = this.parseRetryAfter(res.headers.get(
|
|
284
|
+
this.requeueChunk(chunk);
|
|
285
|
+
const h = (_b = this.parseRetryAfter(res.headers.get('retry-after'))) !== null && _b !== void 0 ? _b : 0;
|
|
142
286
|
const b = this.circuit.remainingCooldownMs();
|
|
143
|
-
const wait = Math.max(h, b, 1000);
|
|
144
|
-
this.opts.warn(`429
|
|
287
|
+
const wait = Math.max(this.retryFloorMs(), h, b, 1000);
|
|
288
|
+
this.opts.warn(`Rate limited (429), will retry ${chunk.length} event(s) in ${wait}ms (circuit: ${this.circuit.getState()}, retry #${this.consecutiveRetries})`);
|
|
145
289
|
this.scheduleFlushIn(wait);
|
|
146
290
|
}
|
|
147
291
|
else {
|
|
148
|
-
this.opts.warn(
|
|
292
|
+
this.opts.warn('Throttle received but client resetting/disabled — dropping chunk');
|
|
149
293
|
}
|
|
150
294
|
return;
|
|
151
295
|
}
|
|
152
296
|
if (s === 401 || s === 403 || s === 404) {
|
|
153
|
-
this.
|
|
154
|
-
this.queue.length = 0;
|
|
155
|
-
this.stop();
|
|
156
|
-
(_d = (_c = this.opts).onFatalConfig) === null || _d === void 0 ? void 0 : _d.call(_c);
|
|
297
|
+
this.handleFatalConfig(s);
|
|
157
298
|
return;
|
|
158
299
|
}
|
|
159
300
|
if (s === 413) {
|
|
@@ -161,13 +302,13 @@ export default class Dispatcher {
|
|
|
161
302
|
if (this.maxBatchSize > 1) {
|
|
162
303
|
this.maxBatchSize = Math.max(1, Math.floor(this.maxBatchSize / 2));
|
|
163
304
|
this.opts.warn(`Payload too large; reducing maxBatchSize to ${this.maxBatchSize}`);
|
|
164
|
-
this.
|
|
305
|
+
this.requeueChunk(chunk);
|
|
165
306
|
this.scheduleFlushIn(500);
|
|
166
307
|
}
|
|
167
308
|
else {
|
|
168
309
|
const ids = chunk
|
|
169
310
|
.map((e) => e.messageId)
|
|
170
|
-
.join(
|
|
311
|
+
.join(',');
|
|
171
312
|
this.opts.warn(`Dropping oversize event(s) after 413 at batchSize=1; messageIds=${ids}`);
|
|
172
313
|
}
|
|
173
314
|
return;
|
|
@@ -179,29 +320,87 @@ export default class Dispatcher {
|
|
|
179
320
|
}
|
|
180
321
|
// Success
|
|
181
322
|
this.circuit.onSuccess();
|
|
182
|
-
this.
|
|
323
|
+
this.consecutiveRetries = 0;
|
|
324
|
+
if (this.maxBatchSize < this.initialMaxBatchSize) {
|
|
325
|
+
this.maxBatchSize = Math.min(this.maxBatchSize * 2, this.initialMaxBatchSize);
|
|
326
|
+
}
|
|
327
|
+
this.opts.log('API call successful');
|
|
328
|
+
// If queue is now empty after this successful batch, fire onFlushComplete
|
|
329
|
+
if (this.queue.length === 0 && this.opts.isNetworkAvailable()) {
|
|
330
|
+
(_d = (_c = this.opts).onFlushComplete) === null || _d === void 0 ? void 0 : _d.call(_c);
|
|
331
|
+
}
|
|
183
332
|
}
|
|
184
333
|
catch (err) {
|
|
185
334
|
this.circuit.onFailure();
|
|
335
|
+
this.consecutiveRetries += 1;
|
|
186
336
|
if (this.opts.isOperational()) {
|
|
187
|
-
this.
|
|
188
|
-
const wait = Math.max(this.circuit.remainingCooldownMs(), 1000);
|
|
189
|
-
this.opts.warn(
|
|
337
|
+
this.requeueChunk(chunk);
|
|
338
|
+
const wait = Math.max(this.retryFloorMs(), this.circuit.remainingCooldownMs(), 1000);
|
|
339
|
+
this.opts.warn(`API call failed: ${err === null || err === void 0 ? void 0 : err.message}, ${chunk.length} event(s) pending retry in ${wait}ms (circuit: ${this.circuit.getState()}, retry #${this.consecutiveRetries})`);
|
|
190
340
|
this.scheduleFlushIn(wait);
|
|
191
341
|
}
|
|
192
342
|
else {
|
|
193
|
-
this.opts.warn(
|
|
343
|
+
this.opts.warn('Flush failed during reset/disable — dropping current chunk');
|
|
194
344
|
}
|
|
195
345
|
return;
|
|
196
346
|
}
|
|
197
347
|
}
|
|
198
|
-
this.opts.log("Flush completed successfully");
|
|
199
348
|
};
|
|
200
349
|
this.flushInFlight = doFlush().finally(() => {
|
|
201
350
|
this.flushInFlight = null;
|
|
202
351
|
});
|
|
203
352
|
return this.flushInFlight;
|
|
204
353
|
}
|
|
354
|
+
resetCircuitBreaker() {
|
|
355
|
+
this.circuit.reset();
|
|
356
|
+
this.consecutiveRetries = 0;
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Coordinate shutdown on a fatal config error (401/403/404).
|
|
360
|
+
* Called by the main flush path and by the disk drain so both paths
|
|
361
|
+
* converge to the same "disable client" signal.
|
|
362
|
+
*/
|
|
363
|
+
handleFatalConfig(statusCode) {
|
|
364
|
+
var _a, _b;
|
|
365
|
+
this.opts.error(`Fatal config error ${statusCode}. Disabling client.`);
|
|
366
|
+
this.queue.length = 0;
|
|
367
|
+
this.queueSizeBytes = 0;
|
|
368
|
+
this.stop();
|
|
369
|
+
(_b = (_a = this.opts).onFatalConfig) === null || _b === void 0 ? void 0 : _b.call(_a);
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Send a batch directly to network, bypassing the memory queue.
|
|
373
|
+
* Used by the disk drain to send events without loading them into the queue.
|
|
374
|
+
* Returns { statusCode } on HTTP response, null on network/transport error.
|
|
375
|
+
*/
|
|
376
|
+
async sendBatchDirect(events) {
|
|
377
|
+
try {
|
|
378
|
+
const nowIso = new Date().toISOString();
|
|
379
|
+
const batch = events.map((e) => ({ ...e, sentAt: nowIso }));
|
|
380
|
+
const headers = {
|
|
381
|
+
'Content-Type': 'application/json',
|
|
382
|
+
};
|
|
383
|
+
if (this.opts.isTracingEnabled()) {
|
|
384
|
+
headers.Trace = 'true';
|
|
385
|
+
}
|
|
386
|
+
const res = await this.opts.fetchWithTimeout(this.opts.endpoint('/v1/batch'), {
|
|
387
|
+
method: 'POST',
|
|
388
|
+
headers,
|
|
389
|
+
body: JSON.stringify({ batch }),
|
|
390
|
+
}, 8000);
|
|
391
|
+
if (res.ok) {
|
|
392
|
+
this.opts.log(`Direct batch send successful (${events.length} events)`);
|
|
393
|
+
}
|
|
394
|
+
else {
|
|
395
|
+
this.opts.warn(`Direct batch send failed with status ${res.status}`);
|
|
396
|
+
}
|
|
397
|
+
return { statusCode: res.status };
|
|
398
|
+
}
|
|
399
|
+
catch (err) {
|
|
400
|
+
this.opts.warn(`Direct batch send failed: ${err === null || err === void 0 ? void 0 : err.message}`);
|
|
401
|
+
return null;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
205
404
|
getDebugInfo() {
|
|
206
405
|
return {
|
|
207
406
|
queueLength: this.queue.length,
|
|
@@ -210,8 +409,12 @@ export default class Dispatcher {
|
|
|
210
409
|
flushInFlight: !!this.flushInFlight,
|
|
211
410
|
circuitState: this.circuit.getState(),
|
|
212
411
|
circuitRemainingMs: this.circuit.remainingCooldownMs(),
|
|
213
|
-
maxQueueEvents: this.opts.
|
|
412
|
+
maxQueueEvents: this.opts.maxEventCount,
|
|
214
413
|
maxBatchSize: this.maxBatchSize,
|
|
414
|
+
consecutiveRetries: this.consecutiveRetries,
|
|
415
|
+
isNetworkAvailable: this.opts.isNetworkAvailable(),
|
|
215
416
|
};
|
|
216
417
|
}
|
|
217
418
|
}
|
|
419
|
+
Dispatcher.encoder = new TextEncoder();
|
|
420
|
+
export default Dispatcher;
|
package/lib/analytics/init.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/analytics/init.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/analytics/init.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAM/D,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,WAAW,GACnB,kBAAkB,CA2CpB"}
|
package/lib/analytics/init.js
CHANGED
|
@@ -1,9 +1,17 @@
|
|
|
1
|
-
import { MetaRouterAnalyticsClient } from
|
|
2
|
-
import { proxyClient, setRealClient } from
|
|
1
|
+
import { MetaRouterAnalyticsClient } from './MetaRouterAnalyticsClient';
|
|
2
|
+
import { proxyClient, setRealClient } from './proxy/proxyClient';
|
|
3
3
|
// Only one initialization in flight
|
|
4
4
|
let initPromise = null;
|
|
5
|
+
let currentOptions = null;
|
|
5
6
|
export function createAnalyticsClient(options) {
|
|
7
|
+
// Check if options have changed - if so, force reset first
|
|
8
|
+
const optionsChanged = currentOptions &&
|
|
9
|
+
JSON.stringify(currentOptions) !== JSON.stringify(options);
|
|
10
|
+
if (optionsChanged && initPromise) {
|
|
11
|
+
console.warn('[MetaRouter] Config changed but client not reset. Call await client.reset() before reinitializing with new options.');
|
|
12
|
+
}
|
|
6
13
|
if (!initPromise) {
|
|
14
|
+
currentOptions = options;
|
|
7
15
|
initPromise = (async () => {
|
|
8
16
|
const instance = new MetaRouterAnalyticsClient(options);
|
|
9
17
|
await instance.init();
|
|
@@ -19,11 +27,13 @@ export function createAnalyticsClient(options) {
|
|
|
19
27
|
setTracing: (enabled) => instance.setTracing(enabled),
|
|
20
28
|
enableDebugLogging: () => instance.enableDebugLogging(),
|
|
21
29
|
getDebugInfo: () => instance.getDebugInfo(),
|
|
30
|
+
getAnonymousId: () => instance.getAnonymousId(),
|
|
22
31
|
flush: () => instance.flush(),
|
|
23
32
|
reset: async () => {
|
|
24
33
|
await instance.reset();
|
|
25
34
|
setRealClient(null, { dropPending: true });
|
|
26
35
|
initPromise = null;
|
|
36
|
+
currentOptions = null;
|
|
27
37
|
},
|
|
28
38
|
};
|
|
29
39
|
setRealClient(boundClient);
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare function exists(): Promise<boolean>;
|
|
2
|
+
export declare function readSnapshot(): Promise<string | null>;
|
|
3
|
+
export declare function writeSnapshot(data: string): Promise<void>;
|
|
4
|
+
export declare function deleteSnapshot(): Promise<void>;
|
|
5
|
+
//# sourceMappingURL=NativeQueueStorage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NativeQueueStorage.d.ts","sourceRoot":"","sources":["../../../src/analytics/persistence/NativeQueueStorage.ts"],"names":[],"mappings":"AAmCA,wBAAsB,MAAM,IAAI,OAAO,CAAC,OAAO,CAAC,CAS/C;AAED,wBAAsB,YAAY,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAS3D;AAED,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAa/D;AAED,wBAAsB,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC,CASpD"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { NativeModules } from 'react-native';
|
|
2
|
+
import { warn } from '../utils/logger';
|
|
3
|
+
function getModule() {
|
|
4
|
+
const mod = NativeModules.MetaRouterQueueStorage;
|
|
5
|
+
if (!mod) {
|
|
6
|
+
warn('MetaRouterQueueStorage native module is not available. Queue persistence is disabled.');
|
|
7
|
+
return null;
|
|
8
|
+
}
|
|
9
|
+
return mod;
|
|
10
|
+
}
|
|
11
|
+
export async function exists() {
|
|
12
|
+
const mod = getModule();
|
|
13
|
+
if (!(mod === null || mod === void 0 ? void 0 : mod.exists))
|
|
14
|
+
return false;
|
|
15
|
+
try {
|
|
16
|
+
return await mod.exists();
|
|
17
|
+
}
|
|
18
|
+
catch (err) {
|
|
19
|
+
warn('Failed to check queue snapshot existence:', err);
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export async function readSnapshot() {
|
|
24
|
+
const mod = getModule();
|
|
25
|
+
if (!mod)
|
|
26
|
+
return null;
|
|
27
|
+
try {
|
|
28
|
+
return await mod.readSnapshot();
|
|
29
|
+
}
|
|
30
|
+
catch (err) {
|
|
31
|
+
warn('Failed to read queue snapshot from disk:', err);
|
|
32
|
+
throw err;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export async function writeSnapshot(data) {
|
|
36
|
+
const mod = getModule();
|
|
37
|
+
if (!mod) {
|
|
38
|
+
throw new Error('MetaRouterQueueStorage native module is not available; cannot write queue snapshot.');
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
await mod.writeSnapshot(data);
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
warn('Failed to write queue snapshot to disk:', err);
|
|
45
|
+
throw err;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export async function deleteSnapshot() {
|
|
49
|
+
const mod = getModule();
|
|
50
|
+
if (!mod)
|
|
51
|
+
return;
|
|
52
|
+
try {
|
|
53
|
+
await mod.deleteSnapshot();
|
|
54
|
+
}
|
|
55
|
+
catch (err) {
|
|
56
|
+
warn('Failed to delete queue snapshot from disk:', err);
|
|
57
|
+
throw err;
|
|
58
|
+
}
|
|
59
|
+
}
|