@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,11 +1,14 @@
|
|
|
1
|
-
import { AppState } from
|
|
2
|
-
import { log, setDebugLogging, warn, error } from
|
|
3
|
-
import { IdentityManager } from
|
|
4
|
-
import { enrichEvent } from
|
|
5
|
-
import { getContextInfo, clearContextCache } from
|
|
6
|
-
import { getIdentityField, setIdentityField, removeIdentityField, ADVERTISING_ID_KEY } from
|
|
7
|
-
import CircuitBreaker from
|
|
8
|
-
import Dispatcher from
|
|
1
|
+
import { AppState } from 'react-native';
|
|
2
|
+
import { log, setDebugLogging, warn, error } from './utils/logger';
|
|
3
|
+
import { IdentityManager } from './IdentityManager';
|
|
4
|
+
import { enrichEvent } from './utils/enrichEvent';
|
|
5
|
+
import { getContextInfo, clearContextCache } from './utils/contextInfo';
|
|
6
|
+
import { getIdentityField, setIdentityField, removeIdentityField, ADVERTISING_ID_KEY, } from './utils/identityStorage';
|
|
7
|
+
import CircuitBreaker from './utils/circuitBreaker';
|
|
8
|
+
import Dispatcher from './dispatcher';
|
|
9
|
+
import { PersistentEventQueue } from './persistence/PersistentEventQueue';
|
|
10
|
+
import { NetworkMonitor, } from './utils/networkMonitor';
|
|
11
|
+
import { DebouncedNetworkMonitor } from './utils/debouncedNetworkMonitor';
|
|
9
12
|
/**
|
|
10
13
|
* Analytics client for MetaRouter.
|
|
11
14
|
* - Handles event queueing, batching, and delivery with retries.
|
|
@@ -18,36 +21,46 @@ export class MetaRouterAnalyticsClient {
|
|
|
18
21
|
* Initializes the analytics client with the provided options.
|
|
19
22
|
* @param options - The initialization options.
|
|
20
23
|
*/
|
|
21
|
-
constructor(options) {
|
|
22
|
-
var _a, _b;
|
|
23
|
-
this.lifecycle =
|
|
24
|
+
constructor(options, deps) {
|
|
25
|
+
var _a, _b, _c, _d;
|
|
26
|
+
this.lifecycle = 'idle';
|
|
24
27
|
this.initPromise = null;
|
|
25
28
|
this.queue = [];
|
|
26
29
|
this.flushIntervalSeconds = 10;
|
|
27
30
|
this.appState = AppState.currentState;
|
|
28
31
|
this.appStateSubscription = null;
|
|
29
|
-
this.
|
|
32
|
+
this.maxDiskEvents = MetaRouterAnalyticsClient.DEFAULT_MAX_DISK_EVENTS;
|
|
30
33
|
this.tracingEnabled = false;
|
|
34
|
+
this.networkStatus = 'connected';
|
|
35
|
+
this.unsubscribeNetwork = null;
|
|
31
36
|
/**
|
|
32
37
|
* Handles the app state change event.
|
|
33
38
|
* @param nextState - The new app state.
|
|
34
39
|
*/
|
|
35
|
-
this.handleAppStateChange = (nextState) => {
|
|
36
|
-
if (this.appState ===
|
|
37
|
-
|
|
38
|
-
this.stopFlushLoop();
|
|
39
|
-
this.clearNextTimer();
|
|
40
|
+
this.handleAppStateChange = async (nextState) => {
|
|
41
|
+
if (this.appState === 'active' && nextState.match(/inactive|background/)) {
|
|
42
|
+
log('App moved to background');
|
|
43
|
+
this.stopFlushLoop();
|
|
44
|
+
this.clearNextTimer();
|
|
45
|
+
try {
|
|
46
|
+
await this.flush();
|
|
47
|
+
await this.persistentQueue.flushToDisk();
|
|
48
|
+
await this.persistentQueue.flushPendingDiskWrites();
|
|
49
|
+
}
|
|
50
|
+
catch (err) {
|
|
51
|
+
warn('Failed to persist queue while moving to background:', err);
|
|
52
|
+
}
|
|
40
53
|
}
|
|
41
|
-
if (nextState ===
|
|
42
|
-
|
|
54
|
+
if (nextState === 'active' && this.lifecycle === 'ready') {
|
|
55
|
+
log('App moved to foreground');
|
|
56
|
+
this.startFlushLoop();
|
|
43
57
|
this.flush();
|
|
44
58
|
}
|
|
45
59
|
this.appState = nextState;
|
|
46
60
|
};
|
|
47
|
-
log("Initializing analytics client", options);
|
|
48
61
|
const { writeKey, ingestionHost, flushIntervalSeconds } = options;
|
|
49
|
-
if (!writeKey || typeof writeKey !==
|
|
50
|
-
throw new Error(
|
|
62
|
+
if (!writeKey || typeof writeKey !== 'string' || writeKey.trim() === '') {
|
|
63
|
+
throw new Error('MetaRouterAnalyticsClient initialization failed: `writeKey` is required and must be a non-empty string.');
|
|
51
64
|
}
|
|
52
65
|
try {
|
|
53
66
|
// Validate it's a proper absolute URL
|
|
@@ -56,28 +69,49 @@ export class MetaRouterAnalyticsClient {
|
|
|
56
69
|
// but "https://example.com/" or "https://example.com/api/" are not.
|
|
57
70
|
// eslint-disable-next-line no-new
|
|
58
71
|
new URL(ingestionHost);
|
|
59
|
-
if (ingestionHost.endsWith(
|
|
72
|
+
if (ingestionHost.endsWith('/')) {
|
|
60
73
|
throw new Error();
|
|
61
74
|
}
|
|
62
75
|
}
|
|
63
76
|
catch {
|
|
64
|
-
throw new Error(
|
|
77
|
+
throw new Error('MetaRouterAnalyticsClient initialization failed: `ingestionHost` must be a valid URL and not end in a slash.');
|
|
65
78
|
}
|
|
66
79
|
this.ingestionHost = ingestionHost;
|
|
67
80
|
this.writeKey = writeKey;
|
|
68
81
|
this.flushIntervalSeconds = flushIntervalSeconds !== null && flushIntervalSeconds !== void 0 ? flushIntervalSeconds : 10;
|
|
69
|
-
|
|
82
|
+
// Validate + normalize persistence caps.
|
|
83
|
+
const rawMaxDisk = (_a = options.maxDiskEvents) !== null && _a !== void 0 ? _a : MetaRouterAnalyticsClient.DEFAULT_MAX_DISK_EVENTS;
|
|
84
|
+
if (rawMaxDisk < 0) {
|
|
85
|
+
throw new Error('MetaRouterAnalyticsClient initialization failed: `maxDiskEvents` must be >= 0 (use 0 to disable disk persistence).');
|
|
86
|
+
}
|
|
87
|
+
this.maxDiskEvents = rawMaxDisk;
|
|
88
|
+
const rawMaxQueue = (_b = options.maxQueueEvents) !== null && _b !== void 0 ? _b : MetaRouterAnalyticsClient.DEFAULT_MAX_QUEUE_EVENTS;
|
|
89
|
+
const maxQueueEvents = Math.max(1, rawMaxQueue);
|
|
90
|
+
if (this.maxDiskEvents > 0 && this.maxDiskEvents < maxQueueEvents) {
|
|
91
|
+
warn(`maxDiskEvents (${this.maxDiskEvents}) is less than maxQueueEvents (${maxQueueEvents}) — memory can hold more events than disk can preserve; events may be dropped during background flush`);
|
|
92
|
+
}
|
|
93
|
+
setDebugLogging((_c = options.debug) !== null && _c !== void 0 ? _c : false);
|
|
70
94
|
this.identityManager = new IdentityManager();
|
|
71
|
-
|
|
95
|
+
// Default: wrap the raw native monitor with the asymmetric debounce
|
|
96
|
+
// (immediate offline, 2s stable-online). If a caller injects their own
|
|
97
|
+
// monitor (e.g. in tests), use it as-is so they control the debounce
|
|
98
|
+
// behavior explicitly.
|
|
99
|
+
this.networkMonitor =
|
|
100
|
+
(_d = deps === null || deps === void 0 ? void 0 : deps.networkMonitor) !== null && _d !== void 0 ? _d : new DebouncedNetworkMonitor(new NetworkMonitor());
|
|
72
101
|
this.dispatcher = new Dispatcher({
|
|
73
|
-
|
|
74
|
-
|
|
102
|
+
maxEventCount: maxQueueEvents,
|
|
103
|
+
maxQueueBytes: MetaRouterAnalyticsClient.MAX_QUEUE_BYTES,
|
|
104
|
+
autoFlushThreshold: MetaRouterAnalyticsClient.AUTO_FLUSH_THRESHOLD,
|
|
75
105
|
maxBatchSize: 100,
|
|
76
106
|
flushIntervalSeconds: this.flushIntervalSeconds,
|
|
107
|
+
baseRetryDelayMs: 1000,
|
|
108
|
+
maxRetryDelayMs: 8000,
|
|
109
|
+
isPersistenceEnabled: () => this.maxDiskEvents > 0,
|
|
110
|
+
isNetworkAvailable: () => this.networkStatus === 'connected',
|
|
77
111
|
endpoint: (path) => this.endpoint(path),
|
|
78
112
|
fetchWithTimeout: (url, init, timeoutMs) => this.fetchWithTimeout(url, init, timeoutMs),
|
|
79
|
-
canSend: () => this.lifecycle ===
|
|
80
|
-
isOperational: () => this.lifecycle ===
|
|
113
|
+
canSend: () => this.lifecycle === 'ready' && !!this.identityManager.getAnonymousId(),
|
|
114
|
+
isOperational: () => this.lifecycle === 'ready',
|
|
81
115
|
isTracingEnabled: () => this.tracingEnabled,
|
|
82
116
|
createBreaker: () => new CircuitBreaker({
|
|
83
117
|
failureThreshold: 3,
|
|
@@ -89,68 +123,99 @@ export class MetaRouterAnalyticsClient {
|
|
|
89
123
|
log(`[MetaRouter] Circuit ${prev} → ${next}` +
|
|
90
124
|
(meta.cooldownMs != null
|
|
91
125
|
? ` (cooldown=${meta.cooldownMs}ms)`
|
|
92
|
-
:
|
|
126
|
+
: ''), { failures: meta.failures, openCount: meta.openCount });
|
|
93
127
|
},
|
|
94
128
|
}),
|
|
95
129
|
log,
|
|
96
130
|
warn,
|
|
97
131
|
error,
|
|
132
|
+
onCapacityOverflow: (events) => this.persistentQueue.bufferEventsForDisk(events),
|
|
133
|
+
onFlushToDisk: (events) => this.persistentQueue.flushEventsToDisk(events),
|
|
134
|
+
onFlushComplete: () => {
|
|
135
|
+
if (this.networkStatus === 'connected') {
|
|
136
|
+
void this.persistentQueue.drainDiskToNetwork(this.dispatcher);
|
|
137
|
+
}
|
|
138
|
+
},
|
|
98
139
|
onScheduleFlushIn: (ms) => {
|
|
99
140
|
this.scheduleFlushIn(ms, { fromDispatcher: true });
|
|
100
141
|
},
|
|
101
142
|
onFatalConfig: () => {
|
|
102
|
-
this.lifecycle =
|
|
143
|
+
this.lifecycle = 'disabled';
|
|
103
144
|
},
|
|
104
145
|
});
|
|
105
146
|
this.queue = this.dispatcher.getQueueRef();
|
|
106
|
-
|
|
147
|
+
this.persistentQueue = new PersistentEventQueue(this.dispatcher, {
|
|
148
|
+
maxDiskEvents: this.maxDiskEvents,
|
|
149
|
+
});
|
|
107
150
|
}
|
|
108
151
|
/**
|
|
109
152
|
* Initializes the analytics client.
|
|
110
153
|
* @returns A promise that resolves when the client is initialized.
|
|
111
154
|
*/
|
|
112
155
|
async init() {
|
|
113
|
-
if (this.lifecycle ===
|
|
114
|
-
log(
|
|
156
|
+
if (this.lifecycle === 'ready') {
|
|
157
|
+
log('Analytics client already ready');
|
|
115
158
|
return;
|
|
116
159
|
}
|
|
117
|
-
if (this.lifecycle ===
|
|
118
|
-
log(
|
|
160
|
+
if (this.lifecycle === 'initializing' && this.initPromise) {
|
|
161
|
+
log('Analytics client initialization already in-flight');
|
|
119
162
|
return this.initPromise;
|
|
120
163
|
}
|
|
121
|
-
if (this.lifecycle ===
|
|
122
|
-
warn(
|
|
164
|
+
if (this.lifecycle === 'disabled') {
|
|
165
|
+
warn('Analytics client is disabled — init skipped');
|
|
123
166
|
return;
|
|
124
167
|
}
|
|
125
|
-
this.lifecycle =
|
|
126
|
-
log("Starting analytics client initialization...");
|
|
168
|
+
this.lifecycle = 'initializing';
|
|
127
169
|
this.initPromise = (async () => {
|
|
128
170
|
try {
|
|
129
171
|
await this.identityManager.init();
|
|
130
|
-
|
|
172
|
+
// Cheap existence check — memory queue starts empty. Any on-disk
|
|
173
|
+
// events are drained directly to the network below (if online) via
|
|
174
|
+
// drainDiskToNetwork, avoiding a memory spike from rehydrating a
|
|
175
|
+
// potentially-large backlog.
|
|
176
|
+
await this.persistentQueue.checkForPersistedEvents();
|
|
131
177
|
this.startFlushLoop();
|
|
132
|
-
log("Flush loop started with interval:", this.flushIntervalSeconds, "seconds");
|
|
133
178
|
this.setupAppStateListener();
|
|
134
|
-
log("App state listener setup completed");
|
|
135
179
|
// Load persisted advertising ID if available
|
|
136
180
|
const persistedAdvertisingId = await getIdentityField(ADVERTISING_ID_KEY);
|
|
137
181
|
this.context = await getContextInfo(persistedAdvertisingId || undefined);
|
|
138
|
-
|
|
139
|
-
|
|
182
|
+
this.lifecycle = 'ready';
|
|
183
|
+
// Set initial network state and subscribe to changes
|
|
184
|
+
this.networkStatus = this.networkMonitor.currentStatus;
|
|
185
|
+
this.unsubscribeNetwork = this.networkMonitor.onStatusChange((status) => {
|
|
186
|
+
const wasOffline = this.networkStatus === 'disconnected';
|
|
187
|
+
this.networkStatus = status;
|
|
188
|
+
log(`Network status changed: ${wasOffline ? 'disconnected' : 'connected'} -> ${status}`);
|
|
189
|
+
if (wasOffline && status === 'connected') {
|
|
190
|
+
log('Dispatcher resumed — device is online, triggering flush');
|
|
191
|
+
this.dispatcher.resetCircuitBreaker();
|
|
192
|
+
// (1) Memory queue → network (existing path)
|
|
193
|
+
void this.flush();
|
|
194
|
+
// (2) Disk → network directly (no load into memory queue)
|
|
195
|
+
void this.persistentQueue.drainDiskToNetwork(this.dispatcher);
|
|
196
|
+
}
|
|
197
|
+
else if (status === 'disconnected') {
|
|
198
|
+
log('Dispatcher paused — device is offline');
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
log('MetaRouter SDK initialized');
|
|
202
|
+
// If online at launch with on-disk events, drain them to the network.
|
|
203
|
+
// Memory queue starts empty, so there's no cold-start flush to run.
|
|
204
|
+
if (this.networkStatus === 'connected' &&
|
|
205
|
+
this.persistentQueue.hasDiskData) {
|
|
206
|
+
void this.persistentQueue.drainDiskToNetwork(this.dispatcher);
|
|
140
207
|
}
|
|
141
|
-
this.lifecycle = "ready";
|
|
142
|
-
log("Analytics client initialization completed successfully");
|
|
143
208
|
}
|
|
144
209
|
catch (error) {
|
|
145
|
-
this.lifecycle =
|
|
146
|
-
warn(
|
|
210
|
+
this.lifecycle = 'idle'; // allow retry
|
|
211
|
+
warn('Analytics client initialization failed:', error);
|
|
147
212
|
throw error;
|
|
148
213
|
}
|
|
149
214
|
})();
|
|
150
215
|
return this.initPromise;
|
|
151
216
|
}
|
|
152
217
|
endpoint(path) {
|
|
153
|
-
return `${this.ingestionHost}${path.startsWith(
|
|
218
|
+
return `${this.ingestionHost}${path.startsWith('/') ? path : `/${path}`}`;
|
|
154
219
|
}
|
|
155
220
|
/**
|
|
156
221
|
* Starts the flush loop.
|
|
@@ -159,7 +224,7 @@ export class MetaRouterAnalyticsClient {
|
|
|
159
224
|
this.dispatcher.start();
|
|
160
225
|
}
|
|
161
226
|
isReady() {
|
|
162
|
-
return this.lifecycle ===
|
|
227
|
+
return this.lifecycle === 'ready';
|
|
163
228
|
}
|
|
164
229
|
/**
|
|
165
230
|
* Fetches with a timeout.
|
|
@@ -192,12 +257,18 @@ export class MetaRouterAnalyticsClient {
|
|
|
192
257
|
*/
|
|
193
258
|
enqueue(event) {
|
|
194
259
|
if (!this.isReady()) {
|
|
195
|
-
warn(
|
|
260
|
+
warn('Analytics client is not ready to operate');
|
|
196
261
|
return;
|
|
197
262
|
}
|
|
198
263
|
const eventWithIdentity = this.identityManager.addIdentityInfo(event);
|
|
199
264
|
const enrichedEvent = enrichEvent(eventWithIdentity, this.writeKey, this.context);
|
|
200
265
|
this.dispatcher.enqueue(enrichedEvent);
|
|
266
|
+
// Check if we should flush to disk based on thresholds
|
|
267
|
+
if (this.persistentQueue.shouldFlushToDisk()) {
|
|
268
|
+
void this.persistentQueue.flushToDisk().catch((err) => {
|
|
269
|
+
warn('Failed to flush queue to disk after threshold:', err);
|
|
270
|
+
});
|
|
271
|
+
}
|
|
201
272
|
}
|
|
202
273
|
scheduleFlushIn(ms, opts) {
|
|
203
274
|
if (opts === null || opts === void 0 ? void 0 : opts.fromDispatcher)
|
|
@@ -214,7 +285,7 @@ export class MetaRouterAnalyticsClient {
|
|
|
214
285
|
* Sets up the app state listener.
|
|
215
286
|
*/
|
|
216
287
|
setupAppStateListener() {
|
|
217
|
-
this.appStateSubscription = AppState.addEventListener(
|
|
288
|
+
this.appStateSubscription = AppState.addEventListener('change', this.handleAppStateChange);
|
|
218
289
|
}
|
|
219
290
|
/**
|
|
220
291
|
* Tracks an event.
|
|
@@ -222,9 +293,7 @@ export class MetaRouterAnalyticsClient {
|
|
|
222
293
|
* @param properties - The properties to track.
|
|
223
294
|
*/
|
|
224
295
|
track(event, properties) {
|
|
225
|
-
|
|
226
|
-
this.enqueue({ type: "track", event, properties, timestamp: this.now() });
|
|
227
|
-
log("Event enqueued, queue length:", this.queue.length);
|
|
296
|
+
this.enqueue({ type: 'track', event, properties, timestamp: this.now() });
|
|
228
297
|
}
|
|
229
298
|
/**
|
|
230
299
|
* Identifies a user.
|
|
@@ -232,10 +301,8 @@ export class MetaRouterAnalyticsClient {
|
|
|
232
301
|
* @param traits - The traits to identify the user with.
|
|
233
302
|
*/
|
|
234
303
|
identify(userId, traits) {
|
|
235
|
-
log("Identifying user:", userId, "with traits:", traits);
|
|
236
304
|
this.identityManager.identify(userId);
|
|
237
|
-
this.enqueue({ type:
|
|
238
|
-
log("Identify event enqueued, queue length:", this.queue.length);
|
|
305
|
+
this.enqueue({ type: 'identify', userId, traits, timestamp: this.now() });
|
|
239
306
|
}
|
|
240
307
|
/**
|
|
241
308
|
* Tracks a page view.
|
|
@@ -243,14 +310,12 @@ export class MetaRouterAnalyticsClient {
|
|
|
243
310
|
* @param properties - The properties to track.
|
|
244
311
|
*/
|
|
245
312
|
page(name, properties) {
|
|
246
|
-
log("Tracking page:", name, "with properties:", properties);
|
|
247
313
|
this.enqueue({
|
|
248
|
-
type:
|
|
314
|
+
type: 'page',
|
|
249
315
|
event: name,
|
|
250
316
|
properties,
|
|
251
317
|
timestamp: this.now(),
|
|
252
318
|
});
|
|
253
|
-
log("Page event enqueued, queue length:", this.queue.length);
|
|
254
319
|
}
|
|
255
320
|
/**
|
|
256
321
|
* Groups a user.
|
|
@@ -258,10 +323,8 @@ export class MetaRouterAnalyticsClient {
|
|
|
258
323
|
* @param traits - The traits to group the user with.
|
|
259
324
|
*/
|
|
260
325
|
group(groupId, traits) {
|
|
261
|
-
log("Grouping user:", groupId, "with traits:", traits);
|
|
262
326
|
this.identityManager.group(groupId);
|
|
263
|
-
this.enqueue({ type:
|
|
264
|
-
log("Group event enqueued, queue length:", this.queue.length);
|
|
327
|
+
this.enqueue({ type: 'group', groupId, traits, timestamp: this.now() });
|
|
265
328
|
}
|
|
266
329
|
/**
|
|
267
330
|
* Tracks a screen view.
|
|
@@ -269,14 +332,12 @@ export class MetaRouterAnalyticsClient {
|
|
|
269
332
|
* @param properties - The properties to track.
|
|
270
333
|
*/
|
|
271
334
|
screen(name, properties) {
|
|
272
|
-
log("Tracking screen:", name, "with properties:", properties);
|
|
273
335
|
this.enqueue({
|
|
274
|
-
type:
|
|
336
|
+
type: 'screen',
|
|
275
337
|
event: name,
|
|
276
338
|
properties,
|
|
277
339
|
timestamp: this.now(),
|
|
278
340
|
});
|
|
279
|
-
log("Screen event enqueued, queue length:", this.queue.length);
|
|
280
341
|
}
|
|
281
342
|
/**
|
|
282
343
|
* Alias an anonymous user to a known user ID.
|
|
@@ -284,10 +345,8 @@ export class MetaRouterAnalyticsClient {
|
|
|
284
345
|
* @param newUserId - The new user ID to alias to.
|
|
285
346
|
*/
|
|
286
347
|
alias(newUserId) {
|
|
287
|
-
log("Aliasing user to:", newUserId);
|
|
288
348
|
this.identityManager.identify(newUserId);
|
|
289
|
-
this.enqueue({ type:
|
|
290
|
-
log("Alias event enqueued, queue length:", this.queue.length);
|
|
349
|
+
this.enqueue({ type: 'alias', userId: newUserId, timestamp: this.now() });
|
|
291
350
|
}
|
|
292
351
|
/**
|
|
293
352
|
* Sets the advertising identifier for ad tracking and attribution.
|
|
@@ -301,18 +360,20 @@ export class MetaRouterAnalyticsClient {
|
|
|
301
360
|
*/
|
|
302
361
|
async setAdvertisingId(advertisingId) {
|
|
303
362
|
if (!this.isReady()) {
|
|
304
|
-
warn(
|
|
363
|
+
warn('Analytics client is not ready. Call init() before setAdvertisingId()');
|
|
305
364
|
return;
|
|
306
365
|
}
|
|
307
|
-
if (!advertisingId ||
|
|
308
|
-
|
|
366
|
+
if (!advertisingId ||
|
|
367
|
+
typeof advertisingId !== 'string' ||
|
|
368
|
+
advertisingId.trim() === '') {
|
|
369
|
+
warn('Invalid advertising ID provided. Must be a non-empty string.');
|
|
309
370
|
return;
|
|
310
371
|
}
|
|
311
|
-
log(
|
|
372
|
+
log('Setting advertising ID');
|
|
312
373
|
await setIdentityField(ADVERTISING_ID_KEY, advertisingId);
|
|
313
374
|
clearContextCache();
|
|
314
375
|
this.context = await getContextInfo(advertisingId);
|
|
315
|
-
log(
|
|
376
|
+
log('Advertising ID updated, persisted, and context refreshed');
|
|
316
377
|
}
|
|
317
378
|
/**
|
|
318
379
|
* Clears the advertising identifier from storage and context.
|
|
@@ -323,14 +384,14 @@ export class MetaRouterAnalyticsClient {
|
|
|
323
384
|
*/
|
|
324
385
|
async clearAdvertisingId() {
|
|
325
386
|
if (!this.isReady()) {
|
|
326
|
-
warn(
|
|
387
|
+
warn('Analytics client is not ready. Call init() before clearAdvertisingId()');
|
|
327
388
|
return;
|
|
328
389
|
}
|
|
329
|
-
log(
|
|
390
|
+
log('Clearing advertising ID');
|
|
330
391
|
await removeIdentityField(ADVERTISING_ID_KEY);
|
|
331
392
|
clearContextCache();
|
|
332
393
|
this.context = await getContextInfo();
|
|
333
|
-
log(
|
|
394
|
+
log('Advertising ID cleared from storage and context');
|
|
334
395
|
}
|
|
335
396
|
/**
|
|
336
397
|
* Enable or disable tracing headers on outgoing requests.
|
|
@@ -355,7 +416,22 @@ export class MetaRouterAnalyticsClient {
|
|
|
355
416
|
*/
|
|
356
417
|
enableDebugLogging() {
|
|
357
418
|
setDebugLogging(true);
|
|
358
|
-
log(
|
|
419
|
+
log('Debug logging enabled');
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Returns the current anonymous ID managed by the JS identity layer.
|
|
423
|
+
* Awaits init() if it is still in-flight. Throws only if the client was
|
|
424
|
+
* never initialized or a reset() races with this call.
|
|
425
|
+
*/
|
|
426
|
+
async getAnonymousId() {
|
|
427
|
+
if (this.initPromise) {
|
|
428
|
+
await this.initPromise;
|
|
429
|
+
}
|
|
430
|
+
const id = this.identityManager.getAnonymousId();
|
|
431
|
+
if (!id) {
|
|
432
|
+
throw new Error('getAnonymousId: no anonymous ID available (client was reset or never initialized)');
|
|
433
|
+
}
|
|
434
|
+
return id;
|
|
359
435
|
}
|
|
360
436
|
/**
|
|
361
437
|
* Get current state for debugging
|
|
@@ -366,7 +442,7 @@ export class MetaRouterAnalyticsClient {
|
|
|
366
442
|
lifecycle: this.lifecycle,
|
|
367
443
|
queueLength: d.queueLength,
|
|
368
444
|
ingestionHost: this.ingestionHost,
|
|
369
|
-
writeKey: this.writeKey ?
|
|
445
|
+
writeKey: this.writeKey ? '***' + this.writeKey.slice(-4) : undefined,
|
|
370
446
|
flushIntervalSeconds: this.flushIntervalSeconds,
|
|
371
447
|
anonymousId: this.identityManager.getAnonymousId(),
|
|
372
448
|
userId: this.identityManager.getUserId(),
|
|
@@ -376,7 +452,10 @@ export class MetaRouterAnalyticsClient {
|
|
|
376
452
|
circuitState: d.circuitState,
|
|
377
453
|
circuitRemainingMs: d.circuitRemainingMs,
|
|
378
454
|
maxQueueEvents: d.maxQueueEvents,
|
|
455
|
+
maxDiskEvents: this.maxDiskEvents,
|
|
379
456
|
tracingEnabled: this.tracingEnabled,
|
|
457
|
+
hasDiskData: this.persistentQueue.hasDiskData,
|
|
458
|
+
networkStatus: this.networkStatus,
|
|
380
459
|
};
|
|
381
460
|
}
|
|
382
461
|
/**
|
|
@@ -390,15 +469,20 @@ export class MetaRouterAnalyticsClient {
|
|
|
390
469
|
* Resets the analytics client.
|
|
391
470
|
*/
|
|
392
471
|
async reset() {
|
|
393
|
-
var _a, _b;
|
|
394
|
-
log(
|
|
472
|
+
var _a, _b, _c;
|
|
473
|
+
log('Resetting analytics client');
|
|
395
474
|
// Flip lifecycle first so other paths see we're resetting
|
|
396
|
-
this.lifecycle =
|
|
475
|
+
this.lifecycle = 'resetting';
|
|
476
|
+
// Stop network monitoring
|
|
477
|
+
(_a = this.unsubscribeNetwork) === null || _a === void 0 ? void 0 : _a.call(this);
|
|
478
|
+
this.unsubscribeNetwork = null;
|
|
479
|
+
this.networkMonitor.stop();
|
|
397
480
|
// Stop background work
|
|
398
481
|
this.dispatcher.stop();
|
|
399
|
-
(
|
|
482
|
+
(_c = (_b = this.appStateSubscription) === null || _b === void 0 ? void 0 : _b.remove) === null || _c === void 0 ? void 0 : _c.call(_b);
|
|
400
483
|
this.appStateSubscription = null;
|
|
401
484
|
this.dispatcher.reset();
|
|
485
|
+
await this.persistentQueue.deleteSnapshot();
|
|
402
486
|
// Clear identity (must remove persisted IDs)
|
|
403
487
|
await this.identityManager.reset();
|
|
404
488
|
// Clear advertising ID from storage
|
|
@@ -406,9 +490,14 @@ export class MetaRouterAnalyticsClient {
|
|
|
406
490
|
// Allow a clean future init
|
|
407
491
|
this.initPromise = null;
|
|
408
492
|
// Back to idle: explicit init required
|
|
409
|
-
this.lifecycle =
|
|
493
|
+
this.lifecycle = 'idle';
|
|
410
494
|
this.clearNextTimer();
|
|
411
|
-
log(
|
|
495
|
+
log('Analytics client reset complete');
|
|
412
496
|
}
|
|
413
497
|
}
|
|
414
|
-
MetaRouterAnalyticsClient.
|
|
498
|
+
MetaRouterAnalyticsClient.AUTO_FLUSH_THRESHOLD = 20;
|
|
499
|
+
MetaRouterAnalyticsClient.DEFAULT_MAX_QUEUE_EVENTS = 2000;
|
|
500
|
+
MetaRouterAnalyticsClient.DEFAULT_MAX_DISK_EVENTS = 10000;
|
|
501
|
+
// Byte cap is intentionally internal (parity with iOS/Android). Not a
|
|
502
|
+
// public option. 5MB — revisit only if a customer actually needs to tune.
|
|
503
|
+
MetaRouterAnalyticsClient.MAX_QUEUE_BYTES = 5 * 1024 * 1024;
|
|
@@ -1,11 +1,24 @@
|
|
|
1
1
|
import type { EventPayload } from './types';
|
|
2
2
|
import type CircuitBreaker from './utils/circuitBreaker';
|
|
3
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
|
}
|
|
@@ -28,17 +44,55 @@ export default class Dispatcher {
|
|
|
28
44
|
private maxBatchSize;
|
|
29
45
|
private readonly initialMaxBatchSize;
|
|
30
46
|
private circuit;
|
|
47
|
+
private queueSizeBytes;
|
|
48
|
+
private consecutiveRetries;
|
|
31
49
|
constructor(opts: DispatcherOptions);
|
|
32
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;
|
|
33
62
|
start(): void;
|
|
34
63
|
stop(): void;
|
|
35
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;
|
|
36
70
|
private clearNextTimer;
|
|
37
71
|
scheduleFlushIn(ms: number): void;
|
|
72
|
+
private static encoder;
|
|
73
|
+
private estimateEventSize;
|
|
74
|
+
private handleCapacityOverflow;
|
|
75
|
+
private isOverCap;
|
|
38
76
|
enqueue(event: EventPayload): void;
|
|
77
|
+
enqueueFront(events: EventPayload[]): void;
|
|
78
|
+
getQueueSizeBytes(): number;
|
|
39
79
|
private drainBatch;
|
|
80
|
+
private requeueChunk;
|
|
40
81
|
private parseRetryAfter;
|
|
41
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>;
|
|
42
96
|
getDebugInfo(): {
|
|
43
97
|
queueLength: number;
|
|
44
98
|
flushIntervalSeconds: number;
|
|
@@ -48,6 +102,8 @@ export default class Dispatcher {
|
|
|
48
102
|
circuitRemainingMs: number;
|
|
49
103
|
maxQueueEvents: number;
|
|
50
104
|
maxBatchSize: number;
|
|
105
|
+
consecutiveRetries: number;
|
|
106
|
+
isNetworkAvailable: boolean;
|
|
51
107
|
};
|
|
52
108
|
}
|
|
53
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":"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,eAAe;IAC9B,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,iBAAiB;IAChC,aAAa,EAAE,MAAM,CAAC;IACtB,aAAa,EAAE,MAAM,CAAC;IACtB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,YAAY,EAAE,MAAM,CAAC;IACrB,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