@metarouter/react-native-sdk 1.2.1 → 1.4.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 +110 -1
- package/lib/analytics/MetaRouterAnalyticsClient.d.ts +22 -11
- package/lib/analytics/MetaRouterAnalyticsClient.d.ts.map +1 -1
- package/lib/analytics/MetaRouterAnalyticsClient.js +109 -215
- package/lib/analytics/dispatcher.d.ts +51 -0
- package/lib/analytics/dispatcher.d.ts.map +1 -0
- package/lib/analytics/dispatcher.js +211 -0
- package/lib/analytics/init.d.ts.map +1 -1
- package/lib/analytics/init.js +2 -0
- package/lib/analytics/proxy/proxyClient.d.ts.map +1 -1
- package/lib/analytics/proxy/proxyClient.js +4 -0
- package/lib/analytics/types.d.ts +3 -0
- package/lib/analytics/types.d.ts.map +1 -1
- package/lib/analytics/utils/contextInfo.d.ts +6 -1
- package/lib/analytics/utils/contextInfo.d.ts.map +1 -1
- package/lib/analytics/utils/contextInfo.js +14 -2
- package/lib/analytics/utils/identityStorage.d.ts +1 -0
- package/lib/analytics/utils/identityStorage.d.ts.map +1 -1
- package/lib/analytics/utils/identityStorage.js +1 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -158,8 +158,10 @@ The analytics client provides the following methods:
|
|
|
158
158
|
- `group(groupId: string, traits?: Record<string, any>)`: Group users
|
|
159
159
|
- `screen(name: string, properties?: Record<string, any>)`: Track screen views
|
|
160
160
|
- `alias(newUserId: string)`: Alias user IDs
|
|
161
|
+
- `setAdvertisingId(advertisingId: string)`: Set the advertising identifier (IDFA on iOS, GAID on Android) for ad tracking. See [Advertising ID](#advertising-id-idfagaid) section for usage and compliance requirements
|
|
162
|
+
- `clearAdvertisingId()`: Clear the advertising identifier from storage and context. Useful for GDPR/CCPA compliance when users opt out of ad tracking
|
|
161
163
|
- `flush()`: Flush events immediately
|
|
162
|
-
- `reset()`: Reset analytics state and clear all stored data
|
|
164
|
+
- `reset()`: Reset analytics state and clear all stored data (includes clearing advertising ID)
|
|
163
165
|
- `enableDebugLogging()`: Enable debug logging
|
|
164
166
|
- `getDebugInfo()`: Get current debug information
|
|
165
167
|
|
|
@@ -266,6 +268,113 @@ sentAt semantics: sentAt is stamped when the event is enqueued. If the client is
|
|
|
266
268
|
- `anonymousId` is a stable, persisted UUID for the device/user before identify; it does **not** include timestamps.
|
|
267
269
|
- `messageId` is generated as `<epochMillis>-<uuid>` (e.g., `1734691572843-6f0c7e85-...`) to aid debugging.
|
|
268
270
|
|
|
271
|
+
## Advertising ID (IDFA/GAID)
|
|
272
|
+
|
|
273
|
+
The SDK supports including advertising identifiers (IDFA on iOS, GAID on Android) in event context for ad tracking and attribution purposes.
|
|
274
|
+
|
|
275
|
+
### Usage
|
|
276
|
+
|
|
277
|
+
Use the `setAdvertisingId()` method to set the advertising identifier after initializing the analytics client:
|
|
278
|
+
|
|
279
|
+
```js
|
|
280
|
+
const analytics = await createAnalyticsClient({
|
|
281
|
+
writeKey: "your-write-key",
|
|
282
|
+
ingestionHost: "https://your-ingestion-endpoint.com",
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
// Set advertising ID after initialization
|
|
286
|
+
await analytics.setAdvertisingId("your-advertising-id"); // IDFA on iOS, GAID on Android
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
Once set, the `advertisingId` will be automatically included in the device context of all subsequent events:
|
|
290
|
+
|
|
291
|
+
```json
|
|
292
|
+
{
|
|
293
|
+
"context": {
|
|
294
|
+
"device": {
|
|
295
|
+
"advertisingId": "your-advertising-id",
|
|
296
|
+
"manufacturer": "Apple",
|
|
297
|
+
"model": "iPhone 14",
|
|
298
|
+
...
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
### Privacy & Compliance
|
|
305
|
+
|
|
306
|
+
⚠️ **Important**: Advertising identifiers are Personally Identifiable Information (PII). Before collecting advertising IDs, you must:
|
|
307
|
+
|
|
308
|
+
1. **Obtain User Consent**: Request explicit permission from users before tracking
|
|
309
|
+
2. **Comply with Regulations**: Follow GDPR, CCPA, and other applicable privacy laws
|
|
310
|
+
3. **App Store Requirements**:
|
|
311
|
+
- iOS: Follow Apple's [App Tracking Transparency (ATT)](https://developer.apple.com/documentation/apptrackingtransparency) framework
|
|
312
|
+
- Android: Follow Google Play's [advertising ID policies](https://support.google.com/googleplay/android-developer/answer/6048248)
|
|
313
|
+
|
|
314
|
+
### iOS Example (with ATT)
|
|
315
|
+
|
|
316
|
+
> **Note:** The examples below use third-party libraries for demonstration purposes. You should choose appropriate packages that fit your project's needs and are actively maintained.
|
|
317
|
+
|
|
318
|
+
```js
|
|
319
|
+
import { AppTrackingTransparency } from 'react-native-tracking-transparency';
|
|
320
|
+
import { getAdvertisingId } from '@react-native-community/google-advertiser-id'; // or similar library
|
|
321
|
+
|
|
322
|
+
// Initialize analytics first
|
|
323
|
+
const analytics = await createAnalyticsClient({
|
|
324
|
+
writeKey: "your-write-key",
|
|
325
|
+
ingestionHost: "https://your-ingestion-endpoint.com",
|
|
326
|
+
});
|
|
327
|
+
|
|
328
|
+
// Request tracking permission
|
|
329
|
+
const trackingStatus = await AppTrackingTransparency.requestTrackingAuthorization();
|
|
330
|
+
|
|
331
|
+
if (trackingStatus === 'authorized') {
|
|
332
|
+
// Get and set IDFA only if authorized
|
|
333
|
+
const advertisingId = await getAdvertisingId();
|
|
334
|
+
await analytics.setAdvertisingId(advertisingId);
|
|
335
|
+
}
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
### Android Example
|
|
339
|
+
|
|
340
|
+
```js
|
|
341
|
+
import { getAdvertisingId } from '@react-native-community/google-advertiser-id'; // or similar library
|
|
342
|
+
|
|
343
|
+
// Initialize analytics first
|
|
344
|
+
const analytics = await createAnalyticsClient({
|
|
345
|
+
writeKey: "your-write-key",
|
|
346
|
+
ingestionHost: "https://your-ingestion-endpoint.com",
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
// Check if user has opted out of personalized ads
|
|
350
|
+
const { advertisingId, isLimitAdTrackingEnabled } = await getAdvertisingId();
|
|
351
|
+
|
|
352
|
+
if (!isLimitAdTrackingEnabled && advertisingId) {
|
|
353
|
+
await analytics.setAdvertisingId(advertisingId);
|
|
354
|
+
}
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
### Clearing Advertising ID
|
|
358
|
+
|
|
359
|
+
When users opt out of ad tracking or revoke consent, use `clearAdvertisingId()` to remove the advertising ID from storage and context:
|
|
360
|
+
|
|
361
|
+
```js
|
|
362
|
+
// User opts out of ad tracking
|
|
363
|
+
await analytics.clearAdvertisingId();
|
|
364
|
+
|
|
365
|
+
// All subsequent events will not include advertisingId in context
|
|
366
|
+
analytics.track("Event After Opt Out");
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
**Note:** The `reset()` method also clears the advertising ID along with all other analytics data.
|
|
370
|
+
|
|
371
|
+
### Validation
|
|
372
|
+
|
|
373
|
+
The SDK validates advertising IDs before setting them:
|
|
374
|
+
- Must be a non-empty string
|
|
375
|
+
- Cannot be only whitespace
|
|
376
|
+
- Invalid values are rejected and logged as warnings
|
|
377
|
+
|
|
269
378
|
## License
|
|
270
379
|
|
|
271
380
|
MIT
|
|
@@ -10,8 +10,7 @@ export declare class MetaRouterAnalyticsClient {
|
|
|
10
10
|
private lifecycle;
|
|
11
11
|
private initPromise;
|
|
12
12
|
private queue;
|
|
13
|
-
private
|
|
14
|
-
private flushTimer;
|
|
13
|
+
private flushIntervalSeconds;
|
|
15
14
|
private ingestionHost;
|
|
16
15
|
private writeKey;
|
|
17
16
|
private context;
|
|
@@ -19,12 +18,8 @@ export declare class MetaRouterAnalyticsClient {
|
|
|
19
18
|
private appStateSubscription;
|
|
20
19
|
private identityManager;
|
|
21
20
|
private static readonly MAX_QUEUE_SIZE;
|
|
22
|
-
private flushInFlight;
|
|
23
|
-
private maxBatchSize;
|
|
24
|
-
private circuit;
|
|
25
|
-
private nextTimer;
|
|
26
|
-
private nextScheduledAt;
|
|
27
21
|
private maxQueueEvents;
|
|
22
|
+
private dispatcher;
|
|
28
23
|
/**
|
|
29
24
|
* Initializes the analytics client with the provided options.
|
|
30
25
|
* @param options - The initialization options.
|
|
@@ -41,7 +36,6 @@ export declare class MetaRouterAnalyticsClient {
|
|
|
41
36
|
*/
|
|
42
37
|
private startFlushLoop;
|
|
43
38
|
private isReady;
|
|
44
|
-
private makeBreaker;
|
|
45
39
|
/**
|
|
46
40
|
* Fetches with a timeout.
|
|
47
41
|
* @param url - The URL to fetch.
|
|
@@ -60,11 +54,9 @@ export declare class MetaRouterAnalyticsClient {
|
|
|
60
54
|
* @param event - The event to enqueue.
|
|
61
55
|
*/
|
|
62
56
|
private enqueue;
|
|
63
|
-
private drainBatch;
|
|
64
57
|
private scheduleFlushIn;
|
|
65
58
|
private stopFlushLoop;
|
|
66
59
|
private clearNextTimer;
|
|
67
|
-
private parseRetryAfter;
|
|
68
60
|
/**
|
|
69
61
|
* Sets up the app state listener.
|
|
70
62
|
*/
|
|
@@ -110,6 +102,25 @@ export declare class MetaRouterAnalyticsClient {
|
|
|
110
102
|
* @param newUserId - The new user ID to alias to.
|
|
111
103
|
*/
|
|
112
104
|
alias(newUserId: string): void;
|
|
105
|
+
/**
|
|
106
|
+
* Sets the advertising identifier for ad tracking and attribution.
|
|
107
|
+
* This will update the context for all subsequent events and persist it to storage.
|
|
108
|
+
*
|
|
109
|
+
* ⚠️ Important: Advertising identifiers are Personally Identifiable Information (PII).
|
|
110
|
+
* You must obtain user consent before collecting advertising IDs and comply with
|
|
111
|
+
* GDPR, CCPA, and App Store privacy requirements.
|
|
112
|
+
*
|
|
113
|
+
* @param advertisingId - The advertising identifier (IDFA on iOS, GAID on Android)
|
|
114
|
+
*/
|
|
115
|
+
setAdvertisingId(advertisingId: string): Promise<void>;
|
|
116
|
+
/**
|
|
117
|
+
* Clears the advertising identifier from storage and context.
|
|
118
|
+
* Use this method when users opt out of ad tracking or revoke consent.
|
|
119
|
+
*
|
|
120
|
+
* This is useful for GDPR/CCPA compliance when users want to stop sharing
|
|
121
|
+
* their advertising ID without performing a full analytics reset.
|
|
122
|
+
*/
|
|
123
|
+
clearAdvertisingId(): Promise<void>;
|
|
113
124
|
/**
|
|
114
125
|
* Enable debug logging for troubleshooting
|
|
115
126
|
*/
|
|
@@ -122,7 +133,7 @@ export declare class MetaRouterAnalyticsClient {
|
|
|
122
133
|
queueLength: number;
|
|
123
134
|
ingestionHost: string;
|
|
124
135
|
writeKey: string | undefined;
|
|
125
|
-
|
|
136
|
+
flushIntervalSeconds: number;
|
|
126
137
|
anonymousId: string | null;
|
|
127
138
|
userId: string | undefined;
|
|
128
139
|
groupId: string | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MetaRouterAnalyticsClient.d.ts","sourceRoot":"","sources":["../../src/analytics/MetaRouterAnalyticsClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAA8B,WAAW,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"MetaRouterAnalyticsClient.d.ts","sourceRoot":"","sources":["../../src/analytics/MetaRouterAnalyticsClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAA8B,WAAW,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAU7E;;;;;;GAMG;AACH,qBAAa,yBAAyB;IACpC,OAAO,CAAC,SAAS,CAAqB;IACtC,OAAO,CAAC,WAAW,CAA8B;IACjD,OAAO,CAAC,KAAK,CAAsB;IACnC,OAAO,CAAC,oBAAoB,CAAM;IAClC,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,OAAO,CAAgB;IAC/B,OAAO,CAAC,QAAQ,CAAyC;IACzD,OAAO,CAAC,oBAAoB,CAAwC;IACpE,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAM;IAC5C,OAAO,CAA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;;;;;;;;;;;IAmBlB;;;OAGG;IACG,KAAK;IAIX;;OAEG;IACU,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CA4BpC"}
|
|
@@ -2,8 +2,10 @@ import { AppState } from "react-native";
|
|
|
2
2
|
import { log, setDebugLogging, warn, error } from "./utils/logger";
|
|
3
3
|
import { IdentityManager } from "./IdentityManager";
|
|
4
4
|
import { enrichEvent } from "./utils/enrichEvent";
|
|
5
|
-
import { getContextInfo } from "./utils/contextInfo";
|
|
5
|
+
import { getContextInfo, clearContextCache } from "./utils/contextInfo";
|
|
6
|
+
import { getIdentityField, setIdentityField, removeIdentityField, ADVERTISING_ID_KEY } from "./utils/identityStorage";
|
|
6
7
|
import CircuitBreaker from "./utils/circuitBreaker";
|
|
8
|
+
import Dispatcher from "./dispatcher";
|
|
7
9
|
/**
|
|
8
10
|
* Analytics client for MetaRouter.
|
|
9
11
|
* - Handles event queueing, batching, and delivery with retries.
|
|
@@ -21,14 +23,10 @@ export class MetaRouterAnalyticsClient {
|
|
|
21
23
|
this.lifecycle = "idle";
|
|
22
24
|
this.initPromise = null;
|
|
23
25
|
this.queue = [];
|
|
24
|
-
this.
|
|
25
|
-
this.flushTimer = null;
|
|
26
|
+
this.flushIntervalSeconds = 10;
|
|
26
27
|
this.appState = AppState.currentState;
|
|
27
28
|
this.appStateSubscription = null;
|
|
28
|
-
this.
|
|
29
|
-
this.maxBatchSize = 100;
|
|
30
|
-
this.nextTimer = null;
|
|
31
|
-
this.nextScheduledAt = null;
|
|
29
|
+
this.maxQueueEvents = 2000;
|
|
32
30
|
/**
|
|
33
31
|
* Handles the app state change event.
|
|
34
32
|
* @param nextState - The new app state.
|
|
@@ -66,13 +64,43 @@ export class MetaRouterAnalyticsClient {
|
|
|
66
64
|
}
|
|
67
65
|
this.ingestionHost = ingestionHost;
|
|
68
66
|
this.writeKey = writeKey;
|
|
69
|
-
this.
|
|
70
|
-
? flushIntervalSeconds * 1000
|
|
71
|
-
: 10000;
|
|
67
|
+
this.flushIntervalSeconds = flushIntervalSeconds !== null && flushIntervalSeconds !== void 0 ? flushIntervalSeconds : 10;
|
|
72
68
|
setDebugLogging((_a = options.debug) !== null && _a !== void 0 ? _a : false);
|
|
73
69
|
this.identityManager = new IdentityManager();
|
|
74
|
-
this.
|
|
75
|
-
this.
|
|
70
|
+
this.maxQueueEvents = (_b = options.maxQueueEvents) !== null && _b !== void 0 ? _b : this.maxQueueEvents;
|
|
71
|
+
this.dispatcher = new Dispatcher({
|
|
72
|
+
maxQueueEvents: this.maxQueueEvents,
|
|
73
|
+
autoFlushThreshold: MetaRouterAnalyticsClient.MAX_QUEUE_SIZE,
|
|
74
|
+
maxBatchSize: 100,
|
|
75
|
+
flushIntervalSeconds: this.flushIntervalSeconds,
|
|
76
|
+
endpoint: (path) => this.endpoint(path),
|
|
77
|
+
fetchWithTimeout: (url, init, timeoutMs) => this.fetchWithTimeout(url, init, timeoutMs),
|
|
78
|
+
canSend: () => this.lifecycle === "ready" && !!this.identityManager.getAnonymousId(),
|
|
79
|
+
isOperational: () => this.lifecycle === "ready",
|
|
80
|
+
createBreaker: () => new CircuitBreaker({
|
|
81
|
+
failureThreshold: 3,
|
|
82
|
+
cooldownMs: 10000,
|
|
83
|
+
maxCooldownMs: 120000,
|
|
84
|
+
jitterRatio: 0.2,
|
|
85
|
+
halfOpenMaxConcurrent: 1,
|
|
86
|
+
onStateChange: (prev, next, meta) => {
|
|
87
|
+
log(`[MetaRouter] Circuit ${prev} → ${next}` +
|
|
88
|
+
(meta.cooldownMs != null
|
|
89
|
+
? ` (cooldown=${meta.cooldownMs}ms)`
|
|
90
|
+
: ""), { failures: meta.failures, openCount: meta.openCount });
|
|
91
|
+
},
|
|
92
|
+
}),
|
|
93
|
+
log,
|
|
94
|
+
warn,
|
|
95
|
+
error,
|
|
96
|
+
onScheduleFlushIn: (ms) => {
|
|
97
|
+
this.scheduleFlushIn(ms, { fromDispatcher: true });
|
|
98
|
+
},
|
|
99
|
+
onFatalConfig: () => {
|
|
100
|
+
this.lifecycle = "disabled";
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
this.queue = this.dispatcher.getQueueRef();
|
|
76
104
|
log("Analytics client constructor completed, initialization in progress...");
|
|
77
105
|
}
|
|
78
106
|
/**
|
|
@@ -99,10 +127,15 @@ export class MetaRouterAnalyticsClient {
|
|
|
99
127
|
await this.identityManager.init();
|
|
100
128
|
log("IdentityManager initialized successfully");
|
|
101
129
|
this.startFlushLoop();
|
|
102
|
-
log("Flush loop started with interval:", this.
|
|
130
|
+
log("Flush loop started with interval:", this.flushIntervalSeconds, "seconds");
|
|
103
131
|
this.setupAppStateListener();
|
|
104
132
|
log("App state listener setup completed");
|
|
105
|
-
|
|
133
|
+
// Load persisted advertising ID if available
|
|
134
|
+
const persistedAdvertisingId = await getIdentityField(ADVERTISING_ID_KEY);
|
|
135
|
+
this.context = await getContextInfo(persistedAdvertisingId || undefined);
|
|
136
|
+
if (persistedAdvertisingId) {
|
|
137
|
+
log("Restored advertising ID from storage");
|
|
138
|
+
}
|
|
106
139
|
this.lifecycle = "ready";
|
|
107
140
|
log("Analytics client initialization completed successfully");
|
|
108
141
|
}
|
|
@@ -121,26 +154,11 @@ export class MetaRouterAnalyticsClient {
|
|
|
121
154
|
* Starts the flush loop.
|
|
122
155
|
*/
|
|
123
156
|
startFlushLoop() {
|
|
124
|
-
|
|
125
|
-
clearInterval(this.flushTimer);
|
|
126
|
-
this.flushTimer = setInterval(() => this.flush(), this.flushIntervalMs);
|
|
157
|
+
this.dispatcher.start();
|
|
127
158
|
}
|
|
128
159
|
isReady() {
|
|
129
160
|
return this.lifecycle === "ready";
|
|
130
161
|
}
|
|
131
|
-
makeBreaker() {
|
|
132
|
-
return new CircuitBreaker({
|
|
133
|
-
failureThreshold: 3,
|
|
134
|
-
cooldownMs: 10000,
|
|
135
|
-
maxCooldownMs: 120000,
|
|
136
|
-
jitterRatio: 0.2,
|
|
137
|
-
halfOpenMaxConcurrent: 1,
|
|
138
|
-
onStateChange: (prev, next, meta) => {
|
|
139
|
-
log(`[MetaRouter] Circuit ${prev} → ${next}` +
|
|
140
|
-
(meta.cooldownMs != null ? ` (cooldown=${meta.cooldownMs}ms)` : ""), { failures: meta.failures, openCount: meta.openCount });
|
|
141
|
-
},
|
|
142
|
-
});
|
|
143
|
-
}
|
|
144
162
|
/**
|
|
145
163
|
* Fetches with a timeout.
|
|
146
164
|
* @param url - The URL to fetch.
|
|
@@ -177,64 +195,18 @@ export class MetaRouterAnalyticsClient {
|
|
|
177
195
|
}
|
|
178
196
|
const eventWithIdentity = this.identityManager.addIdentityInfo(event);
|
|
179
197
|
const enrichedEvent = enrichEvent(eventWithIdentity, this.writeKey, this.context);
|
|
180
|
-
|
|
181
|
-
while (this.queue.length >= this.maxQueueEvents) {
|
|
182
|
-
this.queue.shift();
|
|
183
|
-
warn(`[MetaRouter] Queue cap ${this.maxQueueEvents} reached — dropped oldest event`);
|
|
184
|
-
}
|
|
185
|
-
log("Enqueuing event", {
|
|
186
|
-
type: enrichedEvent === null || enrichedEvent === void 0 ? void 0 : enrichedEvent.type,
|
|
187
|
-
messageId: enrichedEvent === null || enrichedEvent === void 0 ? void 0 : enrichedEvent.messageId,
|
|
188
|
-
});
|
|
189
|
-
this.queue.push(enrichedEvent);
|
|
190
|
-
if (this.queue.length >= MetaRouterAnalyticsClient.MAX_QUEUE_SIZE) {
|
|
191
|
-
log(`Event queue reached ${MetaRouterAnalyticsClient.MAX_QUEUE_SIZE}. Flushing queued events.`);
|
|
192
|
-
this.flush();
|
|
193
|
-
}
|
|
198
|
+
this.dispatcher.enqueue(enrichedEvent);
|
|
194
199
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
const batch = this.queue
|
|
198
|
-
.splice(0, n)
|
|
199
|
-
.map((e) => ({ ...e, sentAt: this.now() }));
|
|
200
|
-
return batch;
|
|
201
|
-
}
|
|
202
|
-
scheduleFlushIn(ms) {
|
|
203
|
-
const target = Date.now() + Math.max(0, ms);
|
|
204
|
-
// If we already have a timer sooner or equal, keep it.
|
|
205
|
-
if (this.nextScheduledAt && target >= this.nextScheduledAt - 25)
|
|
200
|
+
scheduleFlushIn(ms, opts) {
|
|
201
|
+
if (opts === null || opts === void 0 ? void 0 : opts.fromDispatcher)
|
|
206
202
|
return;
|
|
207
|
-
|
|
208
|
-
if (this.nextTimer)
|
|
209
|
-
clearTimeout(this.nextTimer);
|
|
210
|
-
this.nextScheduledAt = target;
|
|
211
|
-
this.nextTimer = setTimeout(() => {
|
|
212
|
-
this.nextScheduledAt = null;
|
|
213
|
-
this.nextTimer = null;
|
|
214
|
-
this.flush();
|
|
215
|
-
}, Math.max(0, ms));
|
|
203
|
+
this.dispatcher.scheduleFlushIn(ms);
|
|
216
204
|
}
|
|
217
205
|
stopFlushLoop() {
|
|
218
|
-
|
|
219
|
-
clearInterval(this.flushTimer);
|
|
220
|
-
this.flushTimer = null;
|
|
221
|
-
}
|
|
206
|
+
this.dispatcher.stop();
|
|
222
207
|
}
|
|
223
208
|
clearNextTimer() {
|
|
224
|
-
|
|
225
|
-
clearTimeout(this.nextTimer);
|
|
226
|
-
this.nextTimer = null;
|
|
227
|
-
}
|
|
228
|
-
this.nextScheduledAt = null;
|
|
229
|
-
}
|
|
230
|
-
parseRetryAfter(h) {
|
|
231
|
-
if (!h)
|
|
232
|
-
return null;
|
|
233
|
-
const secs = Number(h);
|
|
234
|
-
if (!Number.isNaN(secs))
|
|
235
|
-
return secs * 1000;
|
|
236
|
-
const dateMs = Date.parse(h);
|
|
237
|
-
return Number.isNaN(dateMs) ? null : Math.max(0, dateMs - Date.now());
|
|
209
|
+
// Timers owned by dispatcher
|
|
238
210
|
}
|
|
239
211
|
/**
|
|
240
212
|
* Sets up the app state listener.
|
|
@@ -315,6 +287,49 @@ export class MetaRouterAnalyticsClient {
|
|
|
315
287
|
this.enqueue({ type: "alias", userId: newUserId, timestamp: this.now() });
|
|
316
288
|
log("Alias event enqueued, queue length:", this.queue.length);
|
|
317
289
|
}
|
|
290
|
+
/**
|
|
291
|
+
* Sets the advertising identifier for ad tracking and attribution.
|
|
292
|
+
* This will update the context for all subsequent events and persist it to storage.
|
|
293
|
+
*
|
|
294
|
+
* ⚠️ Important: Advertising identifiers are Personally Identifiable Information (PII).
|
|
295
|
+
* You must obtain user consent before collecting advertising IDs and comply with
|
|
296
|
+
* GDPR, CCPA, and App Store privacy requirements.
|
|
297
|
+
*
|
|
298
|
+
* @param advertisingId - The advertising identifier (IDFA on iOS, GAID on Android)
|
|
299
|
+
*/
|
|
300
|
+
async setAdvertisingId(advertisingId) {
|
|
301
|
+
if (!this.isReady()) {
|
|
302
|
+
warn("Analytics client is not ready. Call init() before setAdvertisingId()");
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
if (!advertisingId || typeof advertisingId !== 'string' || advertisingId.trim() === '') {
|
|
306
|
+
warn("Invalid advertising ID provided. Must be a non-empty string.");
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
log("Setting advertising ID");
|
|
310
|
+
await setIdentityField(ADVERTISING_ID_KEY, advertisingId);
|
|
311
|
+
clearContextCache();
|
|
312
|
+
this.context = await getContextInfo(advertisingId);
|
|
313
|
+
log("Advertising ID updated, persisted, and context refreshed");
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Clears the advertising identifier from storage and context.
|
|
317
|
+
* Use this method when users opt out of ad tracking or revoke consent.
|
|
318
|
+
*
|
|
319
|
+
* This is useful for GDPR/CCPA compliance when users want to stop sharing
|
|
320
|
+
* their advertising ID without performing a full analytics reset.
|
|
321
|
+
*/
|
|
322
|
+
async clearAdvertisingId() {
|
|
323
|
+
if (!this.isReady()) {
|
|
324
|
+
warn("Analytics client is not ready. Call init() before clearAdvertisingId()");
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
log("Clearing advertising ID");
|
|
328
|
+
await removeIdentityField(ADVERTISING_ID_KEY);
|
|
329
|
+
clearContextCache();
|
|
330
|
+
this.context = await getContextInfo();
|
|
331
|
+
log("Advertising ID cleared from storage and context");
|
|
332
|
+
}
|
|
318
333
|
/**
|
|
319
334
|
* Enable debug logging for troubleshooting
|
|
320
335
|
*/
|
|
@@ -326,21 +341,21 @@ export class MetaRouterAnalyticsClient {
|
|
|
326
341
|
* Get current state for debugging
|
|
327
342
|
*/
|
|
328
343
|
async getDebugInfo() {
|
|
329
|
-
const
|
|
344
|
+
const d = this.dispatcher.getDebugInfo();
|
|
330
345
|
return {
|
|
331
346
|
lifecycle: this.lifecycle,
|
|
332
|
-
queueLength:
|
|
347
|
+
queueLength: d.queueLength,
|
|
333
348
|
ingestionHost: this.ingestionHost,
|
|
334
349
|
writeKey: this.writeKey ? "***" + this.writeKey.slice(-4) : undefined,
|
|
335
|
-
|
|
350
|
+
flushIntervalSeconds: this.flushIntervalSeconds,
|
|
336
351
|
anonymousId: this.identityManager.getAnonymousId(),
|
|
337
352
|
userId: this.identityManager.getUserId(),
|
|
338
353
|
groupId: this.identityManager.getGroupId(),
|
|
339
354
|
proxy: false,
|
|
340
|
-
flushInFlight:
|
|
341
|
-
circuitState:
|
|
342
|
-
circuitRemainingMs:
|
|
343
|
-
maxQueueEvents:
|
|
355
|
+
flushInFlight: d.flushInFlight,
|
|
356
|
+
circuitState: d.circuitState,
|
|
357
|
+
circuitRemainingMs: d.circuitRemainingMs,
|
|
358
|
+
maxQueueEvents: d.maxQueueEvents,
|
|
344
359
|
};
|
|
345
360
|
}
|
|
346
361
|
/**
|
|
@@ -348,126 +363,7 @@ export class MetaRouterAnalyticsClient {
|
|
|
348
363
|
* Singleflight: coalesces concurrent callers.
|
|
349
364
|
*/
|
|
350
365
|
async flush() {
|
|
351
|
-
|
|
352
|
-
return;
|
|
353
|
-
if (this.flushInFlight)
|
|
354
|
-
return this.flushInFlight;
|
|
355
|
-
if (!this.isReady())
|
|
356
|
-
return;
|
|
357
|
-
const anonId = this.identityManager.getAnonymousId();
|
|
358
|
-
if (!anonId) {
|
|
359
|
-
warn("Anonymous ID not yet ready, delaying flush");
|
|
360
|
-
return;
|
|
361
|
-
}
|
|
362
|
-
const doFlush = async () => {
|
|
363
|
-
var _a, _b;
|
|
364
|
-
// Keep sending while there is work. New events enqueued during the loop
|
|
365
|
-
// will be included in this same flush cycle.
|
|
366
|
-
while (this.queue.length) {
|
|
367
|
-
if (!this.circuit.allowRequest()) {
|
|
368
|
-
const state = this.circuit.getState();
|
|
369
|
-
const wait = this.circuit.remainingCooldownMs();
|
|
370
|
-
log(`[MetaRouter] Circuit ${state} — skip; wait ${wait}ms`);
|
|
371
|
-
this.scheduleFlushIn(wait);
|
|
372
|
-
return;
|
|
373
|
-
}
|
|
374
|
-
const chunk = this.drainBatch();
|
|
375
|
-
try {
|
|
376
|
-
log("Making API call to:", this.endpoint("/v1/batch"));
|
|
377
|
-
const res = await this.fetchWithTimeout(this.endpoint("/v1/batch"), {
|
|
378
|
-
method: "POST",
|
|
379
|
-
headers: { "Content-Type": "application/json" },
|
|
380
|
-
body: JSON.stringify({ batch: chunk }),
|
|
381
|
-
}, 8000);
|
|
382
|
-
if (!res.ok) {
|
|
383
|
-
const s = res.status;
|
|
384
|
-
// Retryable (do NOT throw; mark failure once and schedule)
|
|
385
|
-
if (s >= 500 || s === 408) {
|
|
386
|
-
this.circuit.onFailure();
|
|
387
|
-
// ⬇️ Only requeue/schedule if still operable
|
|
388
|
-
if (this.isReady()) {
|
|
389
|
-
this.queue.unshift(...chunk);
|
|
390
|
-
const retryAfter = (_a = this.parseRetryAfter(res.headers.get("retry-after"))) !== null && _a !== void 0 ? _a : 0;
|
|
391
|
-
const wait = Math.max(this.circuit.remainingCooldownMs(), retryAfter, 1000);
|
|
392
|
-
warn(`Retryable status ${s}; scheduling retry in ${wait}ms`);
|
|
393
|
-
this.scheduleFlushIn(wait);
|
|
394
|
-
}
|
|
395
|
-
else {
|
|
396
|
-
warn("Flush aborted during reset/disable — dropping current chunk");
|
|
397
|
-
}
|
|
398
|
-
return;
|
|
399
|
-
}
|
|
400
|
-
if (s === 429) {
|
|
401
|
-
this.circuit.onFailure();
|
|
402
|
-
if (this.isReady()) {
|
|
403
|
-
this.queue.unshift(...chunk);
|
|
404
|
-
const h = (_b = this.parseRetryAfter(res.headers.get("retry-after"))) !== null && _b !== void 0 ? _b : 0;
|
|
405
|
-
const b = this.circuit.remainingCooldownMs();
|
|
406
|
-
const wait = Math.max(h, b, 1000);
|
|
407
|
-
warn(`429 throttled; scheduling in ${wait}ms (retry-after=${h}, breaker=${b})`);
|
|
408
|
-
this.scheduleFlushIn(wait);
|
|
409
|
-
}
|
|
410
|
-
else {
|
|
411
|
-
warn("Throttle received but client resetting/disabled — dropping chunk");
|
|
412
|
-
}
|
|
413
|
-
return;
|
|
414
|
-
}
|
|
415
|
-
// Fatal config
|
|
416
|
-
if (s === 401 || s === 403 || s === 404) {
|
|
417
|
-
error(`Fatal config error ${s}. Disabling client.`);
|
|
418
|
-
this.lifecycle = "disabled";
|
|
419
|
-
this.queue = [];
|
|
420
|
-
this.clearNextTimer();
|
|
421
|
-
this.stopFlushLoop();
|
|
422
|
-
return;
|
|
423
|
-
}
|
|
424
|
-
// Too large: shrink batch and retry later
|
|
425
|
-
if (s === 413) {
|
|
426
|
-
this.circuit.onNonRetryable();
|
|
427
|
-
if (this.maxBatchSize > 1) {
|
|
428
|
-
this.maxBatchSize = Math.max(1, Math.floor(this.maxBatchSize / 2));
|
|
429
|
-
warn(`Payload too large; reducing maxBatchSize to ${this.maxBatchSize}`);
|
|
430
|
-
this.queue.unshift(...chunk);
|
|
431
|
-
this.scheduleFlushIn(500);
|
|
432
|
-
}
|
|
433
|
-
else {
|
|
434
|
-
// Single event still too large — drop with signal
|
|
435
|
-
const ids = chunk.map((e) => e.messageId).join(",");
|
|
436
|
-
warn(`Dropping oversize event(s) after 413 at batchSize=1; messageIds=${ids}`);
|
|
437
|
-
}
|
|
438
|
-
return;
|
|
439
|
-
}
|
|
440
|
-
// Other 4xx: drop bad payload
|
|
441
|
-
this.circuit.onNonRetryable();
|
|
442
|
-
warn(`Dropping batch due to client error ${s}`);
|
|
443
|
-
continue;
|
|
444
|
-
}
|
|
445
|
-
// Success path
|
|
446
|
-
this.circuit.onSuccess();
|
|
447
|
-
log("API call successful");
|
|
448
|
-
// continue loop to send next chunk
|
|
449
|
-
}
|
|
450
|
-
catch (err) {
|
|
451
|
-
// Network/timeout/abort -> single failure mark
|
|
452
|
-
this.circuit.onFailure();
|
|
453
|
-
if (this.isReady()) {
|
|
454
|
-
this.queue.unshift(...chunk);
|
|
455
|
-
const wait = Math.max(this.circuit.remainingCooldownMs(), 1000);
|
|
456
|
-
warn("Flush attempt failed; scheduling retry in", wait, "ms", err === null || err === void 0 ? void 0 : err.message);
|
|
457
|
-
this.scheduleFlushIn(wait);
|
|
458
|
-
}
|
|
459
|
-
else {
|
|
460
|
-
warn("Flush failed during reset/disable — dropping current chunk");
|
|
461
|
-
}
|
|
462
|
-
return;
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
|
-
log("Flush completed successfully");
|
|
466
|
-
};
|
|
467
|
-
this.flushInFlight = doFlush().finally(() => {
|
|
468
|
-
this.flushInFlight = null;
|
|
469
|
-
});
|
|
470
|
-
return this.flushInFlight;
|
|
366
|
+
return this.dispatcher.flush();
|
|
471
367
|
}
|
|
472
368
|
/**
|
|
473
369
|
* Resets the analytics client.
|
|
@@ -478,16 +374,14 @@ export class MetaRouterAnalyticsClient {
|
|
|
478
374
|
// Flip lifecycle first so other paths see we're resetting
|
|
479
375
|
this.lifecycle = "resetting";
|
|
480
376
|
// Stop background work
|
|
481
|
-
|
|
482
|
-
clearInterval(this.flushTimer);
|
|
483
|
-
this.flushTimer = null;
|
|
484
|
-
}
|
|
377
|
+
this.dispatcher.stop();
|
|
485
378
|
(_b = (_a = this.appStateSubscription) === null || _a === void 0 ? void 0 : _a.remove) === null || _b === void 0 ? void 0 : _b.call(_a);
|
|
486
379
|
this.appStateSubscription = null;
|
|
487
|
-
this.
|
|
488
|
-
this.circuit = this.makeBreaker();
|
|
380
|
+
this.dispatcher.reset();
|
|
489
381
|
// Clear identity (must remove persisted IDs)
|
|
490
382
|
await this.identityManager.reset();
|
|
383
|
+
// Clear advertising ID from storage
|
|
384
|
+
await removeIdentityField(ADVERTISING_ID_KEY);
|
|
491
385
|
// Allow a clean future init
|
|
492
386
|
this.initPromise = null;
|
|
493
387
|
// Back to idle: explicit init required
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { EventPayload } from "./types";
|
|
2
|
+
import type CircuitBreaker from "./utils/circuitBreaker";
|
|
3
|
+
export type CircuitState = "CLOSED" | "OPEN" | "HALF_OPEN";
|
|
4
|
+
export interface DispatcherOptions {
|
|
5
|
+
maxQueueEvents: number;
|
|
6
|
+
autoFlushThreshold: number;
|
|
7
|
+
maxBatchSize: number;
|
|
8
|
+
flushIntervalSeconds: number;
|
|
9
|
+
endpoint: (path: string) => string;
|
|
10
|
+
fetchWithTimeout: (url: string, init: RequestInit, timeoutMs: number) => Promise<Response>;
|
|
11
|
+
canSend: () => boolean;
|
|
12
|
+
isOperational: () => boolean;
|
|
13
|
+
createBreaker: () => CircuitBreaker;
|
|
14
|
+
log: (...args: any[]) => void;
|
|
15
|
+
warn: (...args: any[]) => void;
|
|
16
|
+
error: (...args: any[]) => void;
|
|
17
|
+
onScheduleFlushIn?: (ms: number) => void;
|
|
18
|
+
onFatalConfig?: () => void;
|
|
19
|
+
}
|
|
20
|
+
export default class Dispatcher {
|
|
21
|
+
private readonly opts;
|
|
22
|
+
private readonly queue;
|
|
23
|
+
private flushTimer;
|
|
24
|
+
private nextTimer;
|
|
25
|
+
private nextScheduledAt;
|
|
26
|
+
private flushInFlight;
|
|
27
|
+
private maxBatchSize;
|
|
28
|
+
private circuit;
|
|
29
|
+
constructor(opts: DispatcherOptions);
|
|
30
|
+
getQueueRef(): EventPayload[];
|
|
31
|
+
start(): void;
|
|
32
|
+
stop(): void;
|
|
33
|
+
reset(): void;
|
|
34
|
+
private clearNextTimer;
|
|
35
|
+
scheduleFlushIn(ms: number): void;
|
|
36
|
+
enqueue(event: EventPayload): void;
|
|
37
|
+
private drainBatch;
|
|
38
|
+
private parseRetryAfter;
|
|
39
|
+
flush(): Promise<void>;
|
|
40
|
+
getDebugInfo(): {
|
|
41
|
+
queueLength: number;
|
|
42
|
+
flushIntervalSeconds: number;
|
|
43
|
+
proxy: boolean;
|
|
44
|
+
flushInFlight: boolean;
|
|
45
|
+
circuitState: import("./utils/circuitBreaker").CircuitState;
|
|
46
|
+
circuitRemainingMs: number;
|
|
47
|
+
maxQueueEvents: number;
|
|
48
|
+
maxBatchSize: number;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
//# sourceMappingURL=dispatcher.d.ts.map
|
|
@@ -0,0 +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,cAAc,EAAE,MAAM,CAAC;IACvB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,YAAY,EAAE,MAAM,CAAC;IACrB,oBAAoB,EAAE,MAAM,CAAC;IAE7B,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC;IACnC,gBAAgB,EAAE,CAChB,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,WAAW,EACjB,SAAS,EAAE,MAAM,KACd,OAAO,CAAC,QAAQ,CAAC,CAAC;IACvB,OAAO,EAAE,MAAM,OAAO,CAAC;IACvB,aAAa,EAAE,MAAM,OAAO,CAAC;IAC7B,aAAa,EAAE,MAAM,cAAc,CAAC;IAEpC,GAAG,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAC;IAC9B,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAC;IAC/B,KAAK,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAC;IAEhC,iBAAiB,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;IACzC,aAAa,CAAC,EAAE,MAAM,IAAI,CAAC;CAC5B;AAED,MAAM,CAAC,OAAO,OAAO,UAAU;IAC7B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAoB;IACzC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAsB;IAC5C,OAAO,CAAC,UAAU,CAA+B;IACjD,OAAO,CAAC,SAAS,CAA+B;IAChD,OAAO,CAAC,eAAe,CAAuB;IAC9C,OAAO,CAAC,aAAa,CAA8B;IACnD,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,OAAO,CAAiB;gBAEpB,IAAI,EAAE,iBAAiB;IAMnC,WAAW,IAAI,YAAY,EAAE;IAI7B,KAAK,IAAI,IAAI;IAQb,IAAI,IAAI,IAAI;IAQZ,KAAK,IAAI,IAAI;IAOb,OAAO,CAAC,cAAc;IAQtB,eAAe,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;IAejC,OAAO,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI;IAuBlC,OAAO,CAAC,UAAU;IAUlB,OAAO,CAAC,eAAe;IAQjB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAkJ5B,YAAY;;;;;;;;;;CAYb"}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
export default class Dispatcher {
|
|
2
|
+
constructor(opts) {
|
|
3
|
+
this.queue = [];
|
|
4
|
+
this.flushTimer = null;
|
|
5
|
+
this.nextTimer = null;
|
|
6
|
+
this.nextScheduledAt = null;
|
|
7
|
+
this.flushInFlight = null;
|
|
8
|
+
this.opts = opts;
|
|
9
|
+
this.maxBatchSize = Math.max(1, opts.maxBatchSize);
|
|
10
|
+
this.circuit = opts.createBreaker();
|
|
11
|
+
}
|
|
12
|
+
getQueueRef() {
|
|
13
|
+
return this.queue;
|
|
14
|
+
}
|
|
15
|
+
start() {
|
|
16
|
+
if (this.flushTimer)
|
|
17
|
+
clearInterval(this.flushTimer);
|
|
18
|
+
this.flushTimer = setInterval(() => this.flush(), this.opts.flushIntervalSeconds * 1000);
|
|
19
|
+
}
|
|
20
|
+
stop() {
|
|
21
|
+
if (this.flushTimer) {
|
|
22
|
+
clearInterval(this.flushTimer);
|
|
23
|
+
this.flushTimer = null;
|
|
24
|
+
}
|
|
25
|
+
this.clearNextTimer();
|
|
26
|
+
}
|
|
27
|
+
reset() {
|
|
28
|
+
this.stop();
|
|
29
|
+
this.queue.length = 0;
|
|
30
|
+
this.circuit = this.opts.createBreaker();
|
|
31
|
+
this.maxBatchSize = Math.max(1, this.opts.maxBatchSize);
|
|
32
|
+
}
|
|
33
|
+
clearNextTimer() {
|
|
34
|
+
if (this.nextTimer) {
|
|
35
|
+
clearTimeout(this.nextTimer);
|
|
36
|
+
this.nextTimer = null;
|
|
37
|
+
}
|
|
38
|
+
this.nextScheduledAt = null;
|
|
39
|
+
}
|
|
40
|
+
scheduleFlushIn(ms) {
|
|
41
|
+
var _a, _b;
|
|
42
|
+
const target = Date.now() + Math.max(0, ms);
|
|
43
|
+
if (this.nextScheduledAt && target >= this.nextScheduledAt - 25)
|
|
44
|
+
return;
|
|
45
|
+
if (this.nextTimer)
|
|
46
|
+
clearTimeout(this.nextTimer);
|
|
47
|
+
(_b = (_a = this.opts).onScheduleFlushIn) === null || _b === void 0 ? void 0 : _b.call(_a, ms);
|
|
48
|
+
this.nextScheduledAt = target;
|
|
49
|
+
this.nextTimer = setTimeout(() => {
|
|
50
|
+
this.nextScheduledAt = null;
|
|
51
|
+
this.nextTimer = null;
|
|
52
|
+
this.flush();
|
|
53
|
+
}, Math.max(0, ms));
|
|
54
|
+
}
|
|
55
|
+
enqueue(event) {
|
|
56
|
+
// Hard cap: drop oldest until there's room
|
|
57
|
+
while (this.queue.length >= this.opts.maxQueueEvents) {
|
|
58
|
+
this.queue.shift();
|
|
59
|
+
this.opts.warn(`[MetaRouter] Queue cap ${this.opts.maxQueueEvents} reached — dropped oldest event`);
|
|
60
|
+
}
|
|
61
|
+
this.opts.log("Enqueuing event", {
|
|
62
|
+
type: event === null || event === void 0 ? void 0 : event.type,
|
|
63
|
+
messageId: event === null || event === void 0 ? void 0 : event.messageId,
|
|
64
|
+
});
|
|
65
|
+
this.queue.push(event);
|
|
66
|
+
if (this.queue.length >= this.opts.autoFlushThreshold) {
|
|
67
|
+
this.opts.log(`Event queue reached ${this.opts.autoFlushThreshold}. Flushing queued events.`);
|
|
68
|
+
void this.flush();
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
drainBatch() {
|
|
72
|
+
const n = Math.min(this.queue.length, this.maxBatchSize);
|
|
73
|
+
const nowIso = new Date().toISOString();
|
|
74
|
+
const batch = this.queue.splice(0, n).map((e) => ({
|
|
75
|
+
...e,
|
|
76
|
+
sentAt: nowIso,
|
|
77
|
+
}));
|
|
78
|
+
return batch;
|
|
79
|
+
}
|
|
80
|
+
parseRetryAfter(h) {
|
|
81
|
+
if (!h)
|
|
82
|
+
return null;
|
|
83
|
+
const secs = Number(h);
|
|
84
|
+
if (!Number.isNaN(secs))
|
|
85
|
+
return secs * 1000;
|
|
86
|
+
const dateMs = Date.parse(h);
|
|
87
|
+
return Number.isNaN(dateMs) ? null : Math.max(0, dateMs - Date.now());
|
|
88
|
+
}
|
|
89
|
+
async flush() {
|
|
90
|
+
if (!this.queue.length)
|
|
91
|
+
return;
|
|
92
|
+
if (this.flushInFlight)
|
|
93
|
+
return this.flushInFlight;
|
|
94
|
+
if (!this.opts.canSend())
|
|
95
|
+
return;
|
|
96
|
+
const doFlush = async () => {
|
|
97
|
+
var _a, _b, _c, _d;
|
|
98
|
+
while (this.queue.length) {
|
|
99
|
+
if (!this.circuit.allowRequest()) {
|
|
100
|
+
const state = this.circuit.getState();
|
|
101
|
+
const wait = this.circuit.remainingCooldownMs();
|
|
102
|
+
this.opts.log(`[MetaRouter] Circuit ${state} — skip; wait ${wait}ms`);
|
|
103
|
+
this.scheduleFlushIn(wait);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
const chunk = this.drainBatch();
|
|
107
|
+
try {
|
|
108
|
+
this.opts.log("Making API call to:", this.opts.endpoint("/v1/batch"));
|
|
109
|
+
const res = await this.opts.fetchWithTimeout(this.opts.endpoint("/v1/batch"), {
|
|
110
|
+
method: "POST",
|
|
111
|
+
headers: { "Content-Type": "application/json" },
|
|
112
|
+
body: JSON.stringify({ batch: chunk }),
|
|
113
|
+
}, 8000);
|
|
114
|
+
if (!res.ok) {
|
|
115
|
+
const s = res.status;
|
|
116
|
+
// Retryable
|
|
117
|
+
if (s >= 500 || s === 408) {
|
|
118
|
+
this.circuit.onFailure();
|
|
119
|
+
if (this.opts.isOperational()) {
|
|
120
|
+
this.queue.unshift(...chunk);
|
|
121
|
+
const retryAfter = (_a = this.parseRetryAfter(res.headers.get("retry-after"))) !== null && _a !== void 0 ? _a : 0;
|
|
122
|
+
const wait = Math.max(this.circuit.remainingCooldownMs(), retryAfter, 1000);
|
|
123
|
+
this.opts.warn(`Retryable status ${s}; scheduling retry in ${wait}ms`);
|
|
124
|
+
this.scheduleFlushIn(wait);
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
this.opts.warn("Flush aborted during reset/disable — dropping current chunk");
|
|
128
|
+
}
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (s === 429) {
|
|
132
|
+
this.circuit.onFailure();
|
|
133
|
+
if (this.opts.isOperational()) {
|
|
134
|
+
this.queue.unshift(...chunk);
|
|
135
|
+
const h = (_b = this.parseRetryAfter(res.headers.get("retry-after"))) !== null && _b !== void 0 ? _b : 0;
|
|
136
|
+
const b = this.circuit.remainingCooldownMs();
|
|
137
|
+
const wait = Math.max(h, b, 1000);
|
|
138
|
+
this.opts.warn(`429 throttled; scheduling in ${wait}ms (retry-after=${h}, breaker=${b})`);
|
|
139
|
+
this.scheduleFlushIn(wait);
|
|
140
|
+
}
|
|
141
|
+
else {
|
|
142
|
+
this.opts.warn("Throttle received but client resetting/disabled — dropping chunk");
|
|
143
|
+
}
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
if (s === 401 || s === 403 || s === 404) {
|
|
147
|
+
this.opts.error(`Fatal config error ${s}. Disabling client.`);
|
|
148
|
+
this.queue.length = 0;
|
|
149
|
+
this.stop();
|
|
150
|
+
(_d = (_c = this.opts).onFatalConfig) === null || _d === void 0 ? void 0 : _d.call(_c);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
if (s === 413) {
|
|
154
|
+
this.circuit.onNonRetryable();
|
|
155
|
+
if (this.maxBatchSize > 1) {
|
|
156
|
+
this.maxBatchSize = Math.max(1, Math.floor(this.maxBatchSize / 2));
|
|
157
|
+
this.opts.warn(`Payload too large; reducing maxBatchSize to ${this.maxBatchSize}`);
|
|
158
|
+
this.queue.unshift(...chunk);
|
|
159
|
+
this.scheduleFlushIn(500);
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
const ids = chunk
|
|
163
|
+
.map((e) => e.messageId)
|
|
164
|
+
.join(",");
|
|
165
|
+
this.opts.warn(`Dropping oversize event(s) after 413 at batchSize=1; messageIds=${ids}`);
|
|
166
|
+
}
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
// Other 4xx: drop bad payload
|
|
170
|
+
this.circuit.onNonRetryable();
|
|
171
|
+
this.opts.warn(`Dropping batch due to client error ${s}`);
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
// Success
|
|
175
|
+
this.circuit.onSuccess();
|
|
176
|
+
this.opts.log("API call successful");
|
|
177
|
+
}
|
|
178
|
+
catch (err) {
|
|
179
|
+
this.circuit.onFailure();
|
|
180
|
+
if (this.opts.isOperational()) {
|
|
181
|
+
this.queue.unshift(...chunk);
|
|
182
|
+
const wait = Math.max(this.circuit.remainingCooldownMs(), 1000);
|
|
183
|
+
this.opts.warn("Flush attempt failed; scheduling retry in", wait, "ms", err === null || err === void 0 ? void 0 : err.message);
|
|
184
|
+
this.scheduleFlushIn(wait);
|
|
185
|
+
}
|
|
186
|
+
else {
|
|
187
|
+
this.opts.warn("Flush failed during reset/disable — dropping current chunk");
|
|
188
|
+
}
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
this.opts.log("Flush completed successfully");
|
|
193
|
+
};
|
|
194
|
+
this.flushInFlight = doFlush().finally(() => {
|
|
195
|
+
this.flushInFlight = null;
|
|
196
|
+
});
|
|
197
|
+
return this.flushInFlight;
|
|
198
|
+
}
|
|
199
|
+
getDebugInfo() {
|
|
200
|
+
return {
|
|
201
|
+
queueLength: this.queue.length,
|
|
202
|
+
flushIntervalSeconds: this.opts.flushIntervalSeconds,
|
|
203
|
+
proxy: false,
|
|
204
|
+
flushInFlight: !!this.flushInFlight,
|
|
205
|
+
circuitState: this.circuit.getState(),
|
|
206
|
+
circuitRemainingMs: this.circuit.remainingCooldownMs(),
|
|
207
|
+
maxQueueEvents: this.opts.maxQueueEvents,
|
|
208
|
+
maxBatchSize: this.maxBatchSize,
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
}
|
|
@@ -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;AAK/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;AAK/D,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,WAAW,GACnB,kBAAkB,CA2BpB"}
|
package/lib/analytics/init.js
CHANGED
|
@@ -14,6 +14,8 @@ export function createAnalyticsClient(options) {
|
|
|
14
14
|
screen: (name, props) => instance.screen(name, props),
|
|
15
15
|
page: (name, props) => instance.page(name, props),
|
|
16
16
|
alias: (newUserId) => instance.alias(newUserId),
|
|
17
|
+
setAdvertisingId: (advertisingId) => instance.setAdvertisingId(advertisingId),
|
|
18
|
+
clearAdvertisingId: () => instance.clearAdvertisingId(),
|
|
17
19
|
enableDebugLogging: () => instance.enableDebugLogging(),
|
|
18
20
|
getDebugInfo: () => instance.getDebugInfo(),
|
|
19
21
|
flush: () => instance.flush(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"proxyClient.d.ts","sourceRoot":"","sources":["../../../src/analytics/proxy/proxyClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"proxyClient.d.ts","sourceRoot":"","sources":["../../../src/analytics/proxy/proxyClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AA8InD,eAAO,MAAM,WAAW,EAAE,kBAczB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,kBAAkB,GAAG,IAAI,EACjC,IAAI,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,OAAO,CAAA;CAAE,QAqBjC"}
|
|
@@ -4,6 +4,8 @@ let realClient = null;
|
|
|
4
4
|
const ASYNC_METHODS = {
|
|
5
5
|
flush: true,
|
|
6
6
|
getDebugInfo: true,
|
|
7
|
+
setAdvertisingId: true,
|
|
8
|
+
clearAdvertisingId: true,
|
|
7
9
|
};
|
|
8
10
|
const isAsyncMethod = (m) => ASYNC_METHODS[m] === true;
|
|
9
11
|
// One in-flight flush at a time
|
|
@@ -111,6 +113,8 @@ export const proxyClient = {
|
|
|
111
113
|
screen: (name, props) => handleMethodCall("screen", name, props),
|
|
112
114
|
page: (name, props) => handleMethodCall("page", name, props),
|
|
113
115
|
alias: (newUserId) => handleMethodCall("alias", newUserId),
|
|
116
|
+
setAdvertisingId: (advertisingId) => handleMethodCall("setAdvertisingId", advertisingId),
|
|
117
|
+
clearAdvertisingId: () => handleMethodCall("clearAdvertisingId"),
|
|
114
118
|
flush: () => handleMethodCall("flush"),
|
|
115
119
|
reset: () => handleMethodCall("reset"),
|
|
116
120
|
enableDebugLogging: () => handleMethodCall("enableDebugLogging"),
|
package/lib/analytics/types.d.ts
CHANGED
|
@@ -31,6 +31,8 @@ export interface AnalyticsInterface {
|
|
|
31
31
|
screen: (name: string, props?: Record<string, any>) => void;
|
|
32
32
|
page: (name: string, props?: Record<string, any>) => void;
|
|
33
33
|
alias: (newUserId: string) => void;
|
|
34
|
+
setAdvertisingId: (advertisingId: string) => Promise<void>;
|
|
35
|
+
clearAdvertisingId: () => Promise<void>;
|
|
34
36
|
flush: () => Promise<void>;
|
|
35
37
|
reset: () => Promise<void>;
|
|
36
38
|
enableDebugLogging: () => void;
|
|
@@ -48,6 +50,7 @@ export interface EventContext {
|
|
|
48
50
|
model: string;
|
|
49
51
|
name: string;
|
|
50
52
|
type: string;
|
|
53
|
+
advertisingId?: string;
|
|
51
54
|
};
|
|
52
55
|
library: {
|
|
53
56
|
name: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/analytics/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,SAAS,GACjB,OAAO,GACP,UAAU,GACV,OAAO,GACP,QAAQ,GACR,OAAO,GACP,MAAM,CAAC;AAEX,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,SAAS,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MA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ing a refresh on the next getContextInfo call.
|
|
4
|
+
*/
|
|
5
|
+
export declare function clearContextCache(): void;
|
|
2
6
|
/**
|
|
3
7
|
* Gathers and caches device, app, and environment context information for analytics events.
|
|
4
8
|
*
|
|
@@ -7,7 +11,8 @@ import { EventContext } from "../types";
|
|
|
7
11
|
* - Caches the result for the lifetime of the app to avoid redundant async calls.
|
|
8
12
|
* - Returns a context object suitable for event enrichment.
|
|
9
13
|
*
|
|
14
|
+
* @param advertisingId - Optional advertising identifier (IDFA on iOS, GAID on Android) for ad tracking and attribution.
|
|
10
15
|
* @returns {Promise<EventContext>} A promise that resolves to the context information object.
|
|
11
16
|
*/
|
|
12
|
-
export declare function getContextInfo(): Promise<EventContext>;
|
|
17
|
+
export declare function getContextInfo(advertisingId?: string): Promise<EventContext>;
|
|
13
18
|
//# sourceMappingURL=contextInfo.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contextInfo.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/contextInfo.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"contextInfo.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/contextInfo.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAYxC;;GAEG;AACH,wBAAgB,iBAAiB,IAAI,IAAI,CAGxC;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,cAAc,CAAC,aAAa,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC,CAyDlF"}
|
|
@@ -2,6 +2,7 @@ import { Dimensions, PixelRatio, Platform } from "react-native";
|
|
|
2
2
|
import { getTimeZone } from "./timezone";
|
|
3
3
|
import pkg from "../../../package.json";
|
|
4
4
|
let cachedContext = null;
|
|
5
|
+
let cachedAdvertisingId = undefined;
|
|
5
6
|
let DeviceInfo = null;
|
|
6
7
|
try {
|
|
7
8
|
DeviceInfo = require("react-native-device-info");
|
|
@@ -9,6 +10,13 @@ try {
|
|
|
9
10
|
catch {
|
|
10
11
|
DeviceInfo = null;
|
|
11
12
|
}
|
|
13
|
+
/**
|
|
14
|
+
* Clears the cached context information, forcing a refresh on the next getContextInfo call.
|
|
15
|
+
*/
|
|
16
|
+
export function clearContextCache() {
|
|
17
|
+
cachedContext = null;
|
|
18
|
+
cachedAdvertisingId = undefined;
|
|
19
|
+
}
|
|
12
20
|
/**
|
|
13
21
|
* Gathers and caches device, app, and environment context information for analytics events.
|
|
14
22
|
*
|
|
@@ -17,11 +25,13 @@ catch {
|
|
|
17
25
|
* - Caches the result for the lifetime of the app to avoid redundant async calls.
|
|
18
26
|
* - Returns a context object suitable for event enrichment.
|
|
19
27
|
*
|
|
28
|
+
* @param advertisingId - Optional advertising identifier (IDFA on iOS, GAID on Android) for ad tracking and attribution.
|
|
20
29
|
* @returns {Promise<EventContext>} A promise that resolves to the context information object.
|
|
21
30
|
*/
|
|
22
|
-
export async function getContextInfo() {
|
|
31
|
+
export async function getContextInfo(advertisingId) {
|
|
23
32
|
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z;
|
|
24
|
-
if
|
|
33
|
+
// Return cached context only if it exists AND the advertising ID hasn't changed
|
|
34
|
+
if (cachedContext && cachedAdvertisingId === advertisingId)
|
|
25
35
|
return cachedContext;
|
|
26
36
|
let locale = "en-US";
|
|
27
37
|
if (typeof Intl !== "undefined" &&
|
|
@@ -43,6 +53,7 @@ export async function getContextInfo() {
|
|
|
43
53
|
model: (_f = (_e = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getModel) === null || _e === void 0 ? void 0 : _e.call(DeviceInfo)) !== null && _f !== void 0 ? _f : "unknown",
|
|
44
54
|
name: (_h = (await ((_g = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getDeviceName) === null || _g === void 0 ? void 0 : _g.call(DeviceInfo)))) !== null && _h !== void 0 ? _h : "unknown",
|
|
45
55
|
type: ((_j = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getSystemName) === null || _j === void 0 ? void 0 : _j.call(DeviceInfo)) === "Android" ? "android" : "ios",
|
|
56
|
+
...(advertisingId ? { advertisingId } : {}),
|
|
46
57
|
},
|
|
47
58
|
os: {
|
|
48
59
|
name: (_l = (_k = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getSystemName) === null || _k === void 0 ? void 0 : _k.call(DeviceInfo)) !== null && _l !== void 0 ? _l : "unknown",
|
|
@@ -67,5 +78,6 @@ export async function getContextInfo() {
|
|
|
67
78
|
}
|
|
68
79
|
: {}),
|
|
69
80
|
};
|
|
81
|
+
cachedAdvertisingId = advertisingId;
|
|
70
82
|
return cachedContext;
|
|
71
83
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export declare const ANONYMOUS_ID_KEY = "metarouter:anonymous_id";
|
|
2
2
|
export declare const USER_ID_KEY = "metarouter:user_id";
|
|
3
3
|
export declare const GROUP_ID_KEY = "metarouter:group_id";
|
|
4
|
+
export declare const ADVERTISING_ID_KEY = "metarouter:advertising_id";
|
|
4
5
|
export declare function getIdentityField(key: string): Promise<string | null>;
|
|
5
6
|
export declare function setIdentityField(key: string, value: string): Promise<void>;
|
|
6
7
|
export declare function removeIdentityField(key: string): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"identityStorage.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/identityStorage.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,gBAAgB,4BAA4B,CAAC;AAC1D,eAAO,MAAM,WAAW,uBAAuB,CAAC;AAChD,eAAO,MAAM,YAAY,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"identityStorage.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/identityStorage.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,gBAAgB,4BAA4B,CAAC;AAC1D,eAAO,MAAM,WAAW,uBAAuB,CAAC;AAChD,eAAO,MAAM,YAAY,wBAAwB,CAAC;AAClD,eAAO,MAAM,kBAAkB,8BAA8B,CAAC;AAE9D,wBAAsB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAM1E;AAED,wBAAsB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAMhF;AAED,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAMpE"}
|
|
@@ -2,6 +2,7 @@ import AsyncStorage from '@react-native-async-storage/async-storage';
|
|
|
2
2
|
export const ANONYMOUS_ID_KEY = 'metarouter:anonymous_id';
|
|
3
3
|
export const USER_ID_KEY = 'metarouter:user_id';
|
|
4
4
|
export const GROUP_ID_KEY = 'metarouter:group_id';
|
|
5
|
+
export const ADVERTISING_ID_KEY = 'metarouter:advertising_id';
|
|
5
6
|
export async function getIdentityField(key) {
|
|
6
7
|
try {
|
|
7
8
|
return await AsyncStorage.getItem(key);
|