@metarouter/react-native-sdk 1.5.1 → 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 +28 -6
- 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 +57 -1
- package/lib/analytics/dispatcher.d.ts.map +1 -1
- package/lib/analytics/dispatcher.js +231 -32
- package/lib/analytics/init.d.ts +1 -1
- package/lib/analytics/init.d.ts.map +1 -1
- package/lib/analytics/init.js +3 -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 +21 -19
- 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 +6 -3
- package/react-native.config.js +15 -0
|
@@ -1,10 +1,12 @@
|
|
|
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
11
|
this.initialMaxBatchSize = Math.max(1, opts.maxBatchSize);
|
|
10
12
|
this.maxBatchSize = this.initialMaxBatchSize;
|
|
@@ -13,6 +15,23 @@ export default class Dispatcher {
|
|
|
13
15
|
getQueueRef() {
|
|
14
16
|
return this.queue;
|
|
15
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
|
+
}
|
|
16
35
|
start() {
|
|
17
36
|
if (this.flushTimer)
|
|
18
37
|
clearInterval(this.flushTimer);
|
|
@@ -28,9 +47,21 @@ export default class Dispatcher {
|
|
|
28
47
|
reset() {
|
|
29
48
|
this.stop();
|
|
30
49
|
this.queue.length = 0;
|
|
50
|
+
this.queueSizeBytes = 0;
|
|
51
|
+
this.consecutiveRetries = 0;
|
|
31
52
|
this.circuit = this.opts.createBreaker();
|
|
32
53
|
this.maxBatchSize = this.initialMaxBatchSize;
|
|
33
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));
|
|
64
|
+
}
|
|
34
65
|
clearNextTimer() {
|
|
35
66
|
if (this.nextTimer) {
|
|
36
67
|
clearTimeout(this.nextTimer);
|
|
@@ -53,31 +84,119 @@ export default class Dispatcher {
|
|
|
53
84
|
this.flush();
|
|
54
85
|
}, Math.max(0, ms));
|
|
55
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
|
+
}
|
|
56
130
|
enqueue(event) {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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;
|
|
61
144
|
}
|
|
62
|
-
this.opts.log(
|
|
63
|
-
type: event === null || event === void 0 ? void 0 : event.type,
|
|
64
|
-
messageId: event === null || event === void 0 ? void 0 : event.messageId,
|
|
65
|
-
});
|
|
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}"}`);
|
|
66
146
|
this.queue.push(event);
|
|
147
|
+
this.queueSizeBytes += eventSize;
|
|
148
|
+
this.opts.log(`Event enqueued, queue length: ${this.queue.length}`);
|
|
149
|
+
if (this.queue.length >= this.opts.autoFlushThreshold) {
|
|
150
|
+
void this.flush();
|
|
151
|
+
}
|
|
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
|
+
}
|
|
67
172
|
if (this.queue.length >= this.opts.autoFlushThreshold) {
|
|
68
|
-
this.opts.log(`Event queue reached ${this.opts.autoFlushThreshold}. Flushing queued events.`);
|
|
69
173
|
void this.flush();
|
|
70
174
|
}
|
|
71
175
|
}
|
|
176
|
+
getQueueSizeBytes() {
|
|
177
|
+
return this.queueSizeBytes;
|
|
178
|
+
}
|
|
72
179
|
drainBatch() {
|
|
73
180
|
const n = Math.min(this.queue.length, this.maxBatchSize);
|
|
74
181
|
const nowIso = new Date().toISOString();
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
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
|
+
});
|
|
79
187
|
return batch;
|
|
80
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
|
+
}
|
|
81
200
|
parseRetryAfter(h) {
|
|
82
201
|
if (!h)
|
|
83
202
|
return null;
|
|
@@ -92,21 +211,43 @@ export default class Dispatcher {
|
|
|
92
211
|
return;
|
|
93
212
|
if (this.flushInFlight)
|
|
94
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;
|
|
95
219
|
if (!this.opts.canSend())
|
|
96
220
|
return;
|
|
97
221
|
const doFlush = async () => {
|
|
98
222
|
var _a, _b, _c, _d;
|
|
99
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
|
+
}
|
|
100
241
|
if (!this.circuit.allowRequest()) {
|
|
101
242
|
const state = this.circuit.getState();
|
|
102
243
|
const wait = this.circuit.remainingCooldownMs();
|
|
103
|
-
this.opts.
|
|
244
|
+
this.opts.warn(`Circuit breaker ${state}, retrying in ${wait}ms (${this.queue.length} event(s) pending)`);
|
|
104
245
|
this.scheduleFlushIn(wait);
|
|
105
246
|
return;
|
|
106
247
|
}
|
|
107
248
|
const chunk = this.drainBatch();
|
|
108
249
|
try {
|
|
109
|
-
this.opts.log(
|
|
250
|
+
this.opts.log(`Making API call to: ${this.opts.endpoint('/v1/batch')}`);
|
|
110
251
|
const headers = {
|
|
111
252
|
'Content-Type': 'application/json',
|
|
112
253
|
};
|
|
@@ -123,11 +264,12 @@ export default class Dispatcher {
|
|
|
123
264
|
// Retryable
|
|
124
265
|
if (s >= 500 || s === 408) {
|
|
125
266
|
this.circuit.onFailure();
|
|
267
|
+
this.consecutiveRetries += 1;
|
|
126
268
|
if (this.opts.isOperational()) {
|
|
127
|
-
this.
|
|
269
|
+
this.requeueChunk(chunk);
|
|
128
270
|
const retryAfter = (_a = this.parseRetryAfter(res.headers.get('retry-after'))) !== null && _a !== void 0 ? _a : 0;
|
|
129
|
-
const wait = Math.max(this.circuit.remainingCooldownMs(), retryAfter, 1000);
|
|
130
|
-
this.opts.warn(`
|
|
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})`);
|
|
131
273
|
this.scheduleFlushIn(wait);
|
|
132
274
|
}
|
|
133
275
|
else {
|
|
@@ -137,12 +279,13 @@ export default class Dispatcher {
|
|
|
137
279
|
}
|
|
138
280
|
if (s === 429) {
|
|
139
281
|
this.circuit.onFailure();
|
|
282
|
+
this.consecutiveRetries += 1;
|
|
140
283
|
if (this.opts.isOperational()) {
|
|
141
|
-
this.
|
|
284
|
+
this.requeueChunk(chunk);
|
|
142
285
|
const h = (_b = this.parseRetryAfter(res.headers.get('retry-after'))) !== null && _b !== void 0 ? _b : 0;
|
|
143
286
|
const b = this.circuit.remainingCooldownMs();
|
|
144
|
-
const wait = Math.max(h, b, 1000);
|
|
145
|
-
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})`);
|
|
146
289
|
this.scheduleFlushIn(wait);
|
|
147
290
|
}
|
|
148
291
|
else {
|
|
@@ -151,10 +294,7 @@ export default class Dispatcher {
|
|
|
151
294
|
return;
|
|
152
295
|
}
|
|
153
296
|
if (s === 401 || s === 403 || s === 404) {
|
|
154
|
-
this.
|
|
155
|
-
this.queue.length = 0;
|
|
156
|
-
this.stop();
|
|
157
|
-
(_d = (_c = this.opts).onFatalConfig) === null || _d === void 0 ? void 0 : _d.call(_c);
|
|
297
|
+
this.handleFatalConfig(s);
|
|
158
298
|
return;
|
|
159
299
|
}
|
|
160
300
|
if (s === 413) {
|
|
@@ -162,7 +302,7 @@ export default class Dispatcher {
|
|
|
162
302
|
if (this.maxBatchSize > 1) {
|
|
163
303
|
this.maxBatchSize = Math.max(1, Math.floor(this.maxBatchSize / 2));
|
|
164
304
|
this.opts.warn(`Payload too large; reducing maxBatchSize to ${this.maxBatchSize}`);
|
|
165
|
-
this.
|
|
305
|
+
this.requeueChunk(chunk);
|
|
166
306
|
this.scheduleFlushIn(500);
|
|
167
307
|
}
|
|
168
308
|
else {
|
|
@@ -180,17 +320,23 @@ export default class Dispatcher {
|
|
|
180
320
|
}
|
|
181
321
|
// Success
|
|
182
322
|
this.circuit.onSuccess();
|
|
323
|
+
this.consecutiveRetries = 0;
|
|
183
324
|
if (this.maxBatchSize < this.initialMaxBatchSize) {
|
|
184
325
|
this.maxBatchSize = Math.min(this.maxBatchSize * 2, this.initialMaxBatchSize);
|
|
185
326
|
}
|
|
186
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
|
+
}
|
|
187
332
|
}
|
|
188
333
|
catch (err) {
|
|
189
334
|
this.circuit.onFailure();
|
|
335
|
+
this.consecutiveRetries += 1;
|
|
190
336
|
if (this.opts.isOperational()) {
|
|
191
|
-
this.
|
|
192
|
-
const wait = Math.max(this.circuit.remainingCooldownMs(), 1000);
|
|
193
|
-
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})`);
|
|
194
340
|
this.scheduleFlushIn(wait);
|
|
195
341
|
}
|
|
196
342
|
else {
|
|
@@ -199,13 +345,62 @@ export default class Dispatcher {
|
|
|
199
345
|
return;
|
|
200
346
|
}
|
|
201
347
|
}
|
|
202
|
-
this.opts.log('Flush completed successfully');
|
|
203
348
|
};
|
|
204
349
|
this.flushInFlight = doFlush().finally(() => {
|
|
205
350
|
this.flushInFlight = null;
|
|
206
351
|
});
|
|
207
352
|
return this.flushInFlight;
|
|
208
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
|
+
}
|
|
209
404
|
getDebugInfo() {
|
|
210
405
|
return {
|
|
211
406
|
queueLength: this.queue.length,
|
|
@@ -214,8 +409,12 @@ export default class Dispatcher {
|
|
|
214
409
|
flushInFlight: !!this.flushInFlight,
|
|
215
410
|
circuitState: this.circuit.getState(),
|
|
216
411
|
circuitRemainingMs: this.circuit.remainingCooldownMs(),
|
|
217
|
-
maxQueueEvents: this.opts.
|
|
412
|
+
maxQueueEvents: this.opts.maxEventCount,
|
|
218
413
|
maxBatchSize: this.maxBatchSize,
|
|
414
|
+
consecutiveRetries: this.consecutiveRetries,
|
|
415
|
+
isNetworkAvailable: this.opts.isNetworkAvailable(),
|
|
219
416
|
};
|
|
220
417
|
}
|
|
221
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;AAM/D,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,WAAW,GACnB,kBAAkB,
|
|
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,5 +1,5 @@
|
|
|
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
5
|
let currentOptions = null;
|
|
@@ -27,6 +27,7 @@ export function createAnalyticsClient(options) {
|
|
|
27
27
|
setTracing: (enabled) => instance.setTracing(enabled),
|
|
28
28
|
enableDebugLogging: () => instance.enableDebugLogging(),
|
|
29
29
|
getDebugInfo: () => instance.getDebugInfo(),
|
|
30
|
+
getAnonymousId: () => instance.getAnonymousId(),
|
|
30
31
|
flush: () => instance.flush(),
|
|
31
32
|
reset: async () => {
|
|
32
33
|
await instance.reset();
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { EventPayload } from '../types';
|
|
2
|
+
import type Dispatcher from '../dispatcher';
|
|
3
|
+
/**
|
|
4
|
+
* Memory + disk coordination for the event queue.
|
|
5
|
+
*
|
|
6
|
+
* Single disk file (queue.v1.json) backs both crash-safety (background flush)
|
|
7
|
+
* and offline overflow. All native file mutations run through one serialized
|
|
8
|
+
* lane so append, drain, and delete operations cannot interleave.
|
|
9
|
+
*
|
|
10
|
+
* On boot, {@link checkForPersistedEvents} does a cheap existence check and
|
|
11
|
+
* sets {@link hasDiskData}. The in-memory queue starts empty; when online,
|
|
12
|
+
* the dispatcher drains disk events directly to the network via
|
|
13
|
+
* {@link drainDiskToNetwork} instead of rehydrating into memory.
|
|
14
|
+
*/
|
|
15
|
+
export declare class PersistentEventQueue {
|
|
16
|
+
private readonly dispatcher;
|
|
17
|
+
private readonly maxDiskEvents;
|
|
18
|
+
private _hasDiskData;
|
|
19
|
+
/** Serializes every native file mutation: append, drain rewrite/delete, reset delete. */
|
|
20
|
+
private diskMutation;
|
|
21
|
+
/**
|
|
22
|
+
* Capacity overflow happens from a synchronous enqueue path. These events
|
|
23
|
+
* are owned here until a native write succeeds, so a failed write does not
|
|
24
|
+
* silently discard them from JS memory.
|
|
25
|
+
*/
|
|
26
|
+
private pendingDiskEvents;
|
|
27
|
+
private pendingFlushInFlight;
|
|
28
|
+
/** Guards drainDiskToNetwork (read-then-delete semantics). */
|
|
29
|
+
private drainInFlight;
|
|
30
|
+
constructor(dispatcher: Dispatcher, opts?: {
|
|
31
|
+
maxDiskEvents?: number;
|
|
32
|
+
});
|
|
33
|
+
private enqueueDiskMutation;
|
|
34
|
+
private waitForDiskIdle;
|
|
35
|
+
/** True when a disk snapshot existed at boot or was written since. */
|
|
36
|
+
get hasDiskData(): boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Boot-time cheap existence check.
|
|
39
|
+
* Sets {@link hasDiskData} without reading or parsing the snapshot file,
|
|
40
|
+
* so we can decide whether to trigger a drain without paying the cost of
|
|
41
|
+
* loading a potentially-large snapshot into memory.
|
|
42
|
+
*/
|
|
43
|
+
checkForPersistedEvents(): Promise<boolean>;
|
|
44
|
+
/**
|
|
45
|
+
* Flush the in-memory queue to disk (append + cap).
|
|
46
|
+
* Called on app background and when the flush-to-disk threshold is hit.
|
|
47
|
+
* Serialized against other disk writes.
|
|
48
|
+
*
|
|
49
|
+
* No-op when persistence is disabled (maxDiskEvents === 0). Memory queue
|
|
50
|
+
* is left intact so a subsequent foreground flush can still try to send
|
|
51
|
+
* those events; on app kill they are lost (documented tradeoff).
|
|
52
|
+
*/
|
|
53
|
+
flushToDisk(): Promise<void>;
|
|
54
|
+
/**
|
|
55
|
+
* Append explicit events to the disk store (read-merge-cap-write).
|
|
56
|
+
* Called by lifecycle/offline paths that can await disk durability.
|
|
57
|
+
* Serialized against every other disk mutation.
|
|
58
|
+
*
|
|
59
|
+
* No-op when persistence is disabled (maxDiskEvents === 0).
|
|
60
|
+
*/
|
|
61
|
+
flushEventsToDisk(events: EventPayload[]): Promise<void>;
|
|
62
|
+
/**
|
|
63
|
+
* Own events from synchronous overflow paths until they are durable.
|
|
64
|
+
* The write is started immediately but errors are retained in the pending
|
|
65
|
+
* buffer for a later retry instead of being dropped.
|
|
66
|
+
*/
|
|
67
|
+
bufferEventsForDisk(events: EventPayload[]): void;
|
|
68
|
+
flushPendingDiskWrites(): Promise<void>;
|
|
69
|
+
private _flushPendingDiskWrites;
|
|
70
|
+
private appendPendingDiskEvents;
|
|
71
|
+
private _doFlushEventsToDisk;
|
|
72
|
+
/**
|
|
73
|
+
* Check if the queue has crossed a flush-to-disk threshold.
|
|
74
|
+
*/
|
|
75
|
+
shouldFlushToDisk(): boolean;
|
|
76
|
+
/**
|
|
77
|
+
* Drain disk events directly to network in batches. Does NOT load events
|
|
78
|
+
* into the memory queue. Called on offline→online transition and after
|
|
79
|
+
* successful online flushes.
|
|
80
|
+
*
|
|
81
|
+
* Response handling:
|
|
82
|
+
* - 2xx: advances and deletes sent events; restores batch size after 413
|
|
83
|
+
* - 413: halves batch size, retries. Drops at batchSize=1
|
|
84
|
+
* - 5xx/408/429: stops, writes remainder back, retries on next online transition
|
|
85
|
+
* - 401/403/404: fatal, deletes disk store
|
|
86
|
+
* - Other 4xx: drops batch, continues
|
|
87
|
+
*/
|
|
88
|
+
drainDiskToNetwork(dispatcher: Dispatcher): Promise<void>;
|
|
89
|
+
private _doDrainDiskToNetwork;
|
|
90
|
+
/**
|
|
91
|
+
* Delete the disk store (used during reset).
|
|
92
|
+
*/
|
|
93
|
+
deleteSnapshot(): Promise<void>;
|
|
94
|
+
private _readExistingEvents;
|
|
95
|
+
}
|
|
96
|
+
//# sourceMappingURL=PersistentEventQueue.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PersistentEventQueue.d.ts","sourceRoot":"","sources":["../../../src/analytics/persistence/PersistentEventQueue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,KAAK,UAAU,MAAM,eAAe,CAAC;AA2B5C;;;;;;;;;;;GAWG;AACH,qBAAa,oBAAoB;IAC/B,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAa;IACxC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAS;IACvC,OAAO,CAAC,YAAY,CAAkB;IAEtC,yFAAyF;IACzF,OAAO,CAAC,YAAY,CAAoC;IACxD;;;;OAIG;IACH,OAAO,CAAC,iBAAiB,CAAsB;IAC/C,OAAO,CAAC,oBAAoB,CAA8B;IAC1D,8DAA8D;IAC9D,OAAO,CAAC,aAAa,CAA8B;gBAEvC,UAAU,EAAE,UAAU,EAAE,IAAI,CAAC,EAAE;QAAE,aAAa,CAAC,EAAE,MAAM,CAAA;KAAE;IAKrE,OAAO,CAAC,mBAAmB;IAS3B,OAAO,CAAC,eAAe;IAIvB,sEAAsE;IACtE,IAAI,WAAW,IAAI,OAAO,CAEzB;IAED;;;;;OAKG;IACG,uBAAuB,IAAI,OAAO,CAAC,OAAO,CAAC;IAcjD;;;;;;;;OAQG;IACG,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;IAclC;;;;;;OAMG;IACG,iBAAiB,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ9D;;;;OAIG;IACH,mBAAmB,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,IAAI;IAQ3C,sBAAsB,IAAI,OAAO,CAAC,IAAI,CAAC;YAa/B,uBAAuB;IAarC,OAAO,CAAC,uBAAuB;YAWjB,oBAAoB;IAgClC;;OAEG;IACH,iBAAiB,IAAI,OAAO;IAO5B;;;;;;;;;;;OAWG;IACG,kBAAkB,CAAC,UAAU,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;YAkBjD,qBAAqB;IAuKnC;;OAEG;IACG,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC;YAgBvB,mBAAmB;CAiBlC"}
|