@metarouter/react-native-sdk 1.1.3 → 1.1.4
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/lib/analytics/IdentityManager.d.ts +3 -3
- package/lib/analytics/IdentityManager.d.ts.map +1 -1
- package/lib/analytics/IdentityManager.js +24 -20
- package/lib/analytics/MetaRouterAnalyticsClient.d.ts +27 -24
- package/lib/analytics/MetaRouterAnalyticsClient.d.ts.map +1 -1
- package/lib/analytics/MetaRouterAnalyticsClient.js +130 -57
- package/lib/analytics/init.d.ts +1 -7
- package/lib/analytics/init.d.ts.map +1 -1
- package/lib/analytics/init.js +38 -28
- package/lib/analytics/proxy/proxyClient.d.ts +3 -14
- package/lib/analytics/proxy/proxyClient.d.ts.map +1 -1
- package/lib/analytics/proxy/proxyClient.js +79 -27
- package/lib/analytics/types.d.ts +4 -3
- package/lib/analytics/types.d.ts.map +1 -1
- package/lib/analytics/utils/retry.d.ts +7 -15
- package/lib/analytics/utils/retry.d.ts.map +1 -1
- package/lib/analytics/utils/retry.js +8 -16
- package/package.json +1 -1
|
@@ -11,9 +11,9 @@ export declare class IdentityManager {
|
|
|
11
11
|
private userId?;
|
|
12
12
|
private groupId?;
|
|
13
13
|
/**
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
14
|
+
* Initializes the manager by loading or generating an anonymous ID.
|
|
15
|
+
* Should be called before using other methods.
|
|
16
|
+
*/
|
|
17
17
|
init(): Promise<void>;
|
|
18
18
|
/**
|
|
19
19
|
* Retrieves the current anonymous ID.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IdentityManager.d.ts","sourceRoot":"","sources":["../../src/analytics/IdentityManager.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"IdentityManager.d.ts","sourceRoot":"","sources":["../../src/analytics/IdentityManager.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAU1D;;;;;;GAMG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,WAAW,CAAuB;IAC1C,OAAO,CAAC,MAAM,CAAC,CAAS;IACxB,OAAO,CAAC,OAAO,CAAC,CAAS;IAEzB;;;OAGG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAqC3B;;;OAGG;IACH,cAAc,IAAI,MAAM,GAAG,IAAI;IAI/B;;;OAGG;IACG,QAAQ,CAAC,MAAM,EAAE,MAAM;IAU7B;;;OAGG;IACG,KAAK,CAAC,OAAO,EAAE,MAAM;IAU3B;;;OAGG;IACH,SAAS,IAAI,MAAM,GAAG,SAAS;IAI/B;;;OAGG;IACH,UAAU,IAAI,MAAM,GAAG,SAAS;IAIhC;;;;OAIG;IACH,eAAe,CAAC,CAAC,SAAS,YAAY,EAAE,KAAK,EAAE,CAAC,GAAG,iBAAiB;IASpE;;;OAGG;IACG,KAAK;CAaZ"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { log, warn } from "./utils/logger";
|
|
2
|
-
import { USER_ID_KEY, GROUP_ID_KEY, ANONYMOUS_ID_KEY, getIdentityField, setIdentityField, removeIdentityField } from
|
|
2
|
+
import { USER_ID_KEY, GROUP_ID_KEY, ANONYMOUS_ID_KEY, getIdentityField, setIdentityField, removeIdentityField, } from "./utils/identityStorage";
|
|
3
3
|
/**
|
|
4
4
|
* Manages user, group, and anonymous identity for analytics events.
|
|
5
5
|
* - Loads or generates a persistent anonymous ID.
|
|
@@ -12,30 +12,34 @@ export class IdentityManager {
|
|
|
12
12
|
this.anonymousId = null;
|
|
13
13
|
}
|
|
14
14
|
/**
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
15
|
+
* Initializes the manager by loading or generating an anonymous ID.
|
|
16
|
+
* Should be called before using other methods.
|
|
17
|
+
*/
|
|
18
18
|
async init() {
|
|
19
19
|
try {
|
|
20
20
|
const storedAnonId = await getIdentityField(ANONYMOUS_ID_KEY);
|
|
21
21
|
if (!storedAnonId) {
|
|
22
|
-
const newId = `anon-${Date.now()}-${Math.random()
|
|
22
|
+
const newId = `anon-${Date.now()}-${Math.random()
|
|
23
|
+
.toString(36)
|
|
24
|
+
.substring(2, 10)}`;
|
|
23
25
|
await setIdentityField(ANONYMOUS_ID_KEY, newId);
|
|
24
26
|
this.anonymousId = newId;
|
|
25
|
-
log(
|
|
27
|
+
log("Generated and stored new anonymous ID:", newId);
|
|
26
28
|
}
|
|
27
29
|
else {
|
|
28
30
|
this.anonymousId = storedAnonId;
|
|
29
|
-
log(
|
|
31
|
+
log("Loaded stored anonymous ID:", storedAnonId);
|
|
30
32
|
}
|
|
31
|
-
this.userId = await getIdentityField(USER_ID_KEY) || undefined;
|
|
32
|
-
this.groupId = await getIdentityField(GROUP_ID_KEY) || undefined;
|
|
33
|
-
log(
|
|
33
|
+
this.userId = (await getIdentityField(USER_ID_KEY)) || undefined;
|
|
34
|
+
this.groupId = (await getIdentityField(GROUP_ID_KEY)) || undefined;
|
|
35
|
+
log("IdentityManager initialized with anonymous ID:", this.anonymousId, "userId:", this.userId, "groupId:", this.groupId);
|
|
34
36
|
}
|
|
35
37
|
catch (error) {
|
|
36
|
-
warn(
|
|
37
|
-
this.anonymousId = `fallback-${Date.now()}-${Math.random()
|
|
38
|
-
|
|
38
|
+
warn("Failed to initialize IdentityManager, using fallback anonymous ID", error);
|
|
39
|
+
this.anonymousId = `fallback-${Date.now()}-${Math.random()
|
|
40
|
+
.toString(36)
|
|
41
|
+
.substring(2, 10)}`;
|
|
42
|
+
log("Using fallback anonymous ID:", this.anonymousId);
|
|
39
43
|
}
|
|
40
44
|
}
|
|
41
45
|
/**
|
|
@@ -55,9 +59,9 @@ export class IdentityManager {
|
|
|
55
59
|
await setIdentityField(USER_ID_KEY, userId);
|
|
56
60
|
}
|
|
57
61
|
catch (error) {
|
|
58
|
-
warn(
|
|
62
|
+
warn("Failed to persist userId", error);
|
|
59
63
|
}
|
|
60
|
-
log(
|
|
64
|
+
log("User identified:", userId);
|
|
61
65
|
}
|
|
62
66
|
/**
|
|
63
67
|
* Sets the group ID for the current session.
|
|
@@ -69,9 +73,9 @@ export class IdentityManager {
|
|
|
69
73
|
await setIdentityField(GROUP_ID_KEY, groupId);
|
|
70
74
|
}
|
|
71
75
|
catch (error) {
|
|
72
|
-
warn(
|
|
76
|
+
warn("Failed to persist groupId", error);
|
|
73
77
|
}
|
|
74
|
-
log(
|
|
78
|
+
log("User grouped:", groupId);
|
|
75
79
|
}
|
|
76
80
|
/**
|
|
77
81
|
* Retrieves the current user ID.
|
|
@@ -96,7 +100,7 @@ export class IdentityManager {
|
|
|
96
100
|
var _a, _b, _c;
|
|
97
101
|
return {
|
|
98
102
|
...event,
|
|
99
|
-
anonymousId: (_a = this.anonymousId) !== null && _a !== void 0 ? _a :
|
|
103
|
+
anonymousId: (_a = this.anonymousId) !== null && _a !== void 0 ? _a : "unknown",
|
|
100
104
|
userId: (_b = event.userId) !== null && _b !== void 0 ? _b : this.userId,
|
|
101
105
|
groupId: (_c = event.groupId) !== null && _c !== void 0 ? _c : this.groupId,
|
|
102
106
|
};
|
|
@@ -115,8 +119,8 @@ export class IdentityManager {
|
|
|
115
119
|
await removeIdentityField(GROUP_ID_KEY);
|
|
116
120
|
}
|
|
117
121
|
catch (error) {
|
|
118
|
-
warn(
|
|
122
|
+
warn("Failed to clear userId/groupId/anonymousId from storage", error);
|
|
119
123
|
}
|
|
120
|
-
log(
|
|
124
|
+
log("IdentityManager reset");
|
|
121
125
|
}
|
|
122
126
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { InitOptions } from "./types";
|
|
1
|
+
import { InitOptions, Lifecycle } from "./types";
|
|
2
2
|
/**
|
|
3
3
|
* Analytics client for MetaRouter.
|
|
4
4
|
* - Handles event queueing, batching, and delivery with retries.
|
|
@@ -7,7 +7,8 @@ import { InitOptions } from "./types";
|
|
|
7
7
|
* - Provides debug and cleanup utilities.
|
|
8
8
|
*/
|
|
9
9
|
export declare class MetaRouterAnalyticsClient {
|
|
10
|
-
private
|
|
10
|
+
private lifecycle;
|
|
11
|
+
private initPromise;
|
|
11
12
|
private queue;
|
|
12
13
|
private flushIntervalMs;
|
|
13
14
|
private flushTimer;
|
|
@@ -18,6 +19,8 @@ export declare class MetaRouterAnalyticsClient {
|
|
|
18
19
|
private appStateSubscription;
|
|
19
20
|
private identityManager;
|
|
20
21
|
private static readonly MAX_QUEUE_SIZE;
|
|
22
|
+
private flushInFlight;
|
|
23
|
+
private readonly MAX_BATCH_SIZE;
|
|
21
24
|
/**
|
|
22
25
|
* Initializes the analytics client with the provided options.
|
|
23
26
|
* @param options - The initialization options.
|
|
@@ -27,11 +30,24 @@ export declare class MetaRouterAnalyticsClient {
|
|
|
27
30
|
* Initializes the analytics client.
|
|
28
31
|
* @returns A promise that resolves when the client is initialized.
|
|
29
32
|
*/
|
|
30
|
-
|
|
33
|
+
init(): Promise<void>;
|
|
31
34
|
/**
|
|
32
35
|
* Starts the flush loop.
|
|
33
36
|
*/
|
|
34
37
|
private startFlushLoop;
|
|
38
|
+
/**
|
|
39
|
+
* Checks if the analytics client can operate.
|
|
40
|
+
* @returns True if the client is ready to operate, false otherwise.
|
|
41
|
+
*/
|
|
42
|
+
private canOperate;
|
|
43
|
+
/**
|
|
44
|
+
* Fetches with a timeout.
|
|
45
|
+
* @param url - The URL to fetch.
|
|
46
|
+
* @param init - The request init.
|
|
47
|
+
* @param timeoutMs - The timeout in milliseconds.
|
|
48
|
+
* @returns The response.
|
|
49
|
+
*/
|
|
50
|
+
private fetchWithTimeout;
|
|
35
51
|
/**
|
|
36
52
|
* Returns the current timestamp in ISO format.
|
|
37
53
|
* @returns The current timestamp in ISO format.
|
|
@@ -94,8 +110,8 @@ export declare class MetaRouterAnalyticsClient {
|
|
|
94
110
|
/**
|
|
95
111
|
* Get current state for debugging
|
|
96
112
|
*/
|
|
97
|
-
getDebugInfo(): {
|
|
98
|
-
|
|
113
|
+
getDebugInfo(): Promise<{
|
|
114
|
+
lifecycle: Lifecycle;
|
|
99
115
|
queueLength: number;
|
|
100
116
|
ingestionHost: string;
|
|
101
117
|
writeKey: string | undefined;
|
|
@@ -104,27 +120,14 @@ export declare class MetaRouterAnalyticsClient {
|
|
|
104
120
|
userId: string | undefined;
|
|
105
121
|
groupId: string | undefined;
|
|
106
122
|
proxy: boolean;
|
|
107
|
-
}
|
|
123
|
+
}>;
|
|
108
124
|
/**
|
|
109
125
|
* Flushes the event queue to the ingestion endpoint.
|
|
110
126
|
*/
|
|
111
|
-
flush(): Promise<
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
groupId?: string;
|
|
117
|
-
traits?: Record<string, any>;
|
|
118
|
-
properties?: Record<string, any>;
|
|
119
|
-
timestamp?: string;
|
|
120
|
-
}[] | undefined>;
|
|
121
|
-
/**
|
|
122
|
-
* Resets the analytics client:
|
|
123
|
-
* - Clears identity (anonymousId, userId, groupId)
|
|
124
|
-
* - Clears queued events
|
|
125
|
-
* - Stops background flushing
|
|
126
|
-
* - Removes app state listeners
|
|
127
|
-
*/
|
|
128
|
-
reset(): void;
|
|
127
|
+
flush(): Promise<void>;
|
|
128
|
+
/**
|
|
129
|
+
* Resets the analytics client.
|
|
130
|
+
*/
|
|
131
|
+
reset(): Promise<void>;
|
|
129
132
|
}
|
|
130
133
|
//# sourceMappingURL=MetaRouterAnalyticsClient.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MetaRouterAnalyticsClient.d.ts","sourceRoot":"","sources":["../../src/analytics/MetaRouterAnalyticsClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAA8B,WAAW,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"MetaRouterAnalyticsClient.d.ts","sourceRoot":"","sources":["../../src/analytics/MetaRouterAnalyticsClient.ts"],"names":[],"mappings":"AAAA,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EAAE,GAAG,CAAC;IAWnD;;;;OAIG;IACH,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;IAOnD;;;;OAIG;IACH,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;IAWrD;;;;OAIG;IACH,KAAK,CAAC,SAAS,EAAE,MAAM;IAOvB;;OAEG;IACH,kBAAkB;IAKlB;;OAEG;IACG,YAAY;;;;;;;;;;;IAclB;;OAEG;IACG,KAAK;IAuEX;;OAEG;IACU,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CA4BpC"}
|
|
@@ -18,12 +18,15 @@ export class MetaRouterAnalyticsClient {
|
|
|
18
18
|
*/
|
|
19
19
|
constructor(options) {
|
|
20
20
|
var _a;
|
|
21
|
-
this.
|
|
21
|
+
this.lifecycle = "idle";
|
|
22
|
+
this.initPromise = null;
|
|
22
23
|
this.queue = [];
|
|
23
24
|
this.flushIntervalMs = 10000;
|
|
24
25
|
this.flushTimer = null;
|
|
25
26
|
this.appState = AppState.currentState;
|
|
26
27
|
this.appStateSubscription = null;
|
|
28
|
+
this.flushInFlight = null;
|
|
29
|
+
this.MAX_BATCH_SIZE = 100;
|
|
27
30
|
/**
|
|
28
31
|
* Handles the app state change event.
|
|
29
32
|
* @param nextState - The new app state.
|
|
@@ -55,7 +58,6 @@ export class MetaRouterAnalyticsClient {
|
|
|
55
58
|
: 10000;
|
|
56
59
|
setDebugLogging((_a = options.debug) !== null && _a !== void 0 ? _a : false);
|
|
57
60
|
this.identityManager = new IdentityManager();
|
|
58
|
-
this.init();
|
|
59
61
|
log("Analytics client constructor completed, initialization in progress...");
|
|
60
62
|
}
|
|
61
63
|
/**
|
|
@@ -63,28 +65,39 @@ export class MetaRouterAnalyticsClient {
|
|
|
63
65
|
* @returns A promise that resolves when the client is initialized.
|
|
64
66
|
*/
|
|
65
67
|
async init() {
|
|
66
|
-
if (this.
|
|
67
|
-
log("Analytics client already
|
|
68
|
+
if (this.lifecycle === "ready") {
|
|
69
|
+
log("Analytics client already ready");
|
|
68
70
|
return;
|
|
69
71
|
}
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
log("IdentityManager initialized successfully");
|
|
74
|
-
this.startFlushLoop();
|
|
75
|
-
log("Flush loop started with interval:", this.flushIntervalMs, "ms");
|
|
76
|
-
this.setupAppStateListener();
|
|
77
|
-
log("App state listener setup completed");
|
|
78
|
-
this.context = await getContextInfo();
|
|
79
|
-
this.initialized = true;
|
|
80
|
-
log("Analytics client initialization completed successfully");
|
|
72
|
+
if (this.lifecycle === "initializing" && this.initPromise) {
|
|
73
|
+
log("Analytics client initialization already in-flight");
|
|
74
|
+
return this.initPromise;
|
|
81
75
|
}
|
|
82
|
-
|
|
83
|
-
warn("Analytics client
|
|
84
|
-
|
|
85
|
-
this.initialized = true;
|
|
86
|
-
throw error;
|
|
76
|
+
if (this.lifecycle === "disabled") {
|
|
77
|
+
warn("Analytics client is disabled — init skipped");
|
|
78
|
+
return;
|
|
87
79
|
}
|
|
80
|
+
this.lifecycle = "initializing";
|
|
81
|
+
log("Starting analytics client initialization...");
|
|
82
|
+
this.initPromise = (async () => {
|
|
83
|
+
try {
|
|
84
|
+
await this.identityManager.init();
|
|
85
|
+
log("IdentityManager initialized successfully");
|
|
86
|
+
this.startFlushLoop();
|
|
87
|
+
log("Flush loop started with interval:", this.flushIntervalMs, "ms");
|
|
88
|
+
this.setupAppStateListener();
|
|
89
|
+
log("App state listener setup completed");
|
|
90
|
+
this.context = await getContextInfo();
|
|
91
|
+
this.lifecycle = "ready";
|
|
92
|
+
log("Analytics client initialization completed successfully");
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
this.lifecycle = "idle"; // allow retry
|
|
96
|
+
warn("Analytics client initialization failed:", error);
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
})();
|
|
100
|
+
return this.initPromise;
|
|
88
101
|
}
|
|
89
102
|
/**
|
|
90
103
|
* Starts the flush loop.
|
|
@@ -92,6 +105,46 @@ export class MetaRouterAnalyticsClient {
|
|
|
92
105
|
startFlushLoop() {
|
|
93
106
|
this.flushTimer = setInterval(() => this.flush(), this.flushIntervalMs);
|
|
94
107
|
}
|
|
108
|
+
/**
|
|
109
|
+
* Checks if the analytics client can operate.
|
|
110
|
+
* @returns True if the client is ready to operate, false otherwise.
|
|
111
|
+
*/
|
|
112
|
+
canOperate() {
|
|
113
|
+
return this.lifecycle === "ready";
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Fetches with a timeout.
|
|
117
|
+
* @param url - The URL to fetch.
|
|
118
|
+
* @param init - The request init.
|
|
119
|
+
* @param timeoutMs - The timeout in milliseconds.
|
|
120
|
+
* @returns The response.
|
|
121
|
+
*/
|
|
122
|
+
async fetchWithTimeout(url, init, timeoutMs) {
|
|
123
|
+
return new Promise((resolve, reject) => {
|
|
124
|
+
let settled = false;
|
|
125
|
+
const t = setTimeout(() => {
|
|
126
|
+
if (!settled) {
|
|
127
|
+
settled = true;
|
|
128
|
+
reject(new Error(`Fetch timeout after ${timeoutMs}ms`));
|
|
129
|
+
}
|
|
130
|
+
}, timeoutMs);
|
|
131
|
+
fetch(url, init)
|
|
132
|
+
.then((res) => {
|
|
133
|
+
if (!settled) {
|
|
134
|
+
settled = true;
|
|
135
|
+
clearTimeout(t);
|
|
136
|
+
resolve(res);
|
|
137
|
+
}
|
|
138
|
+
})
|
|
139
|
+
.catch((err) => {
|
|
140
|
+
if (!settled) {
|
|
141
|
+
settled = true;
|
|
142
|
+
clearTimeout(t);
|
|
143
|
+
reject(err);
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
}
|
|
95
148
|
/**
|
|
96
149
|
* Returns the current timestamp in ISO format.
|
|
97
150
|
* @returns The current timestamp in ISO format.
|
|
@@ -104,6 +157,10 @@ export class MetaRouterAnalyticsClient {
|
|
|
104
157
|
* @param event - The event to enqueue.
|
|
105
158
|
*/
|
|
106
159
|
enqueue(event) {
|
|
160
|
+
if (!this.canOperate()) {
|
|
161
|
+
warn("Analytics client is not ready to operate");
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
107
164
|
const eventWithIdentity = this.identityManager.addIdentityInfo(event);
|
|
108
165
|
const enrichedEvent = enrichEvent(eventWithIdentity, this.writeKey, this.context);
|
|
109
166
|
log("Enqueuing event", enrichedEvent);
|
|
@@ -202,9 +259,9 @@ export class MetaRouterAnalyticsClient {
|
|
|
202
259
|
/**
|
|
203
260
|
* Get current state for debugging
|
|
204
261
|
*/
|
|
205
|
-
getDebugInfo() {
|
|
262
|
+
async getDebugInfo() {
|
|
206
263
|
return {
|
|
207
|
-
|
|
264
|
+
lifecycle: this.lifecycle,
|
|
208
265
|
queueLength: this.queue.length,
|
|
209
266
|
ingestionHost: this.ingestionHost,
|
|
210
267
|
writeKey: this.writeKey ? "***" + this.writeKey.slice(-4) : undefined,
|
|
@@ -219,69 +276,85 @@ export class MetaRouterAnalyticsClient {
|
|
|
219
276
|
* Flushes the event queue to the ingestion endpoint.
|
|
220
277
|
*/
|
|
221
278
|
async flush() {
|
|
279
|
+
if (!this.canOperate())
|
|
280
|
+
return;
|
|
281
|
+
if (!this.queue.length)
|
|
282
|
+
return;
|
|
283
|
+
if (this.flushInFlight)
|
|
284
|
+
return this.flushInFlight; // coalesce
|
|
222
285
|
const anonId = this.identityManager.getAnonymousId();
|
|
223
286
|
if (!anonId) {
|
|
224
287
|
warn("Anonymous ID not yet ready, delaying flush");
|
|
225
|
-
// Anon ID not yet ready, delay flushing
|
|
226
288
|
return;
|
|
227
289
|
}
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
return;
|
|
231
|
-
}
|
|
232
|
-
const batch = this.queue.map((event) => ({
|
|
233
|
-
...event,
|
|
290
|
+
const batch = this.queue.map((e) => ({
|
|
291
|
+
...e,
|
|
234
292
|
sentAt: new Date().toISOString(),
|
|
235
293
|
}));
|
|
236
|
-
this.queue = [];
|
|
237
|
-
|
|
238
|
-
try {
|
|
294
|
+
this.queue = []; // optimistic clear; we’ll put them back on failure
|
|
295
|
+
const doFlush = async () => {
|
|
239
296
|
await retryWithBackoff(async () => {
|
|
297
|
+
if (!this.canOperate())
|
|
298
|
+
throw new Error("Client not ready during flush");
|
|
240
299
|
log("Making API call to:", this.ingestionHost + "/v1/batch");
|
|
241
|
-
const response = await
|
|
300
|
+
const response = await this.fetchWithTimeout(this.ingestionHost + "/v1/batch", {
|
|
242
301
|
method: "POST",
|
|
243
|
-
headers: {
|
|
244
|
-
"Content-Type": "application/json",
|
|
245
|
-
},
|
|
302
|
+
headers: { "Content-Type": "application/json" },
|
|
246
303
|
body: JSON.stringify({ batch }),
|
|
247
|
-
}
|
|
304
|
+
}, 8000 // timeout per attempt
|
|
305
|
+
);
|
|
248
306
|
if (!response.ok) {
|
|
249
|
-
error("HTTP error", response);
|
|
307
|
+
error("HTTP error", response.status, response.statusText);
|
|
250
308
|
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
251
309
|
}
|
|
252
310
|
log("API call successful, status:", response.status);
|
|
253
|
-
|
|
311
|
+
}, {
|
|
312
|
+
retries: 5,
|
|
313
|
+
baseDelayMs: 1000,
|
|
314
|
+
shouldContinue: () => this.canOperate(),
|
|
254
315
|
});
|
|
255
316
|
log("Flush completed successfully");
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
317
|
+
};
|
|
318
|
+
this.flushInFlight = doFlush()
|
|
319
|
+
.catch((err) => {
|
|
320
|
+
if (this.canOperate()) {
|
|
321
|
+
// Put events back at the **front** in original order
|
|
322
|
+
warn("Flush failed, re-queueing events", err);
|
|
323
|
+
this.queue.unshift(...batch);
|
|
324
|
+
}
|
|
325
|
+
else {
|
|
326
|
+
warn("Flush failed, but client is not ready to operate");
|
|
327
|
+
}
|
|
328
|
+
throw err;
|
|
329
|
+
})
|
|
330
|
+
.finally(() => {
|
|
331
|
+
this.flushInFlight = null;
|
|
332
|
+
});
|
|
333
|
+
return this.flushInFlight;
|
|
262
334
|
}
|
|
263
335
|
/**
|
|
264
|
-
* Resets the analytics client
|
|
265
|
-
* - Clears identity (anonymousId, userId, groupId)
|
|
266
|
-
* - Clears queued events
|
|
267
|
-
* - Stops background flushing
|
|
268
|
-
* - Removes app state listeners
|
|
336
|
+
* Resets the analytics client.
|
|
269
337
|
*/
|
|
270
|
-
reset() {
|
|
338
|
+
async reset() {
|
|
271
339
|
var _a, _b;
|
|
272
340
|
log("Resetting analytics client");
|
|
273
|
-
//
|
|
274
|
-
this.
|
|
275
|
-
//
|
|
276
|
-
this.queue = [];
|
|
277
|
-
// Clear flush interval
|
|
341
|
+
// Flip lifecycle first so other paths see we're resetting
|
|
342
|
+
this.lifecycle = "resetting";
|
|
343
|
+
// Stop background work
|
|
278
344
|
if (this.flushTimer) {
|
|
279
345
|
clearInterval(this.flushTimer);
|
|
280
346
|
this.flushTimer = null;
|
|
281
347
|
}
|
|
282
|
-
// Remove AppState listener
|
|
283
348
|
(_b = (_a = this.appStateSubscription) === null || _a === void 0 ? void 0 : _a.remove) === null || _b === void 0 ? void 0 : _b.call(_a);
|
|
284
349
|
this.appStateSubscription = null;
|
|
350
|
+
// Drop queued events
|
|
351
|
+
this.queue = [];
|
|
352
|
+
// Clear identity (must remove persisted IDs)
|
|
353
|
+
await this.identityManager.reset();
|
|
354
|
+
// Allow a clean future init
|
|
355
|
+
this.initPromise = null;
|
|
356
|
+
// Back to idle: explicit init required
|
|
357
|
+
this.lifecycle = "idle";
|
|
285
358
|
log("Analytics client reset complete");
|
|
286
359
|
}
|
|
287
360
|
}
|
package/lib/analytics/init.d.ts
CHANGED
|
@@ -1,9 +1,3 @@
|
|
|
1
1
|
import type { InitOptions, AnalyticsInterface } from "./types";
|
|
2
|
-
|
|
3
|
-
* Modular factory for creating an independent analytics client.
|
|
4
|
-
* Binds the first created client to the proxy for queued events.
|
|
5
|
-
* @param options Initialization options.
|
|
6
|
-
* @returns A fully initialized analytics interface.
|
|
7
|
-
*/
|
|
8
|
-
export declare function createAnalyticsClient(options: InitOptions): AnalyticsInterface;
|
|
2
|
+
export declare function createAnalyticsClient(options: InitOptions): Promise<AnalyticsInterface>;
|
|
9
3
|
//# sourceMappingURL=init.d.ts.map
|
|
@@ -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
|
|
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,wBAAsB,qBAAqB,CACzC,OAAO,EAAE,WAAW,GACnB,OAAO,CAAC,kBAAkB,CAAC,CAwC7B"}
|
package/lib/analytics/init.js
CHANGED
|
@@ -1,31 +1,41 @@
|
|
|
1
1
|
import { MetaRouterAnalyticsClient } from "./MetaRouterAnalyticsClient";
|
|
2
|
-
import { setRealClient } from "./proxy/proxyClient";
|
|
3
|
-
//
|
|
4
|
-
let
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
2
|
+
import { proxyClient, setRealClient } from "./proxy/proxyClient";
|
|
3
|
+
// Single-flight guard so concurrent callers don't double-init
|
|
4
|
+
let inFlight = null;
|
|
5
|
+
export async function createAnalyticsClient(options) {
|
|
6
|
+
if (inFlight)
|
|
7
|
+
return inFlight;
|
|
8
|
+
inFlight = (async () => {
|
|
9
|
+
// 1) Build the real client and fully initialize it
|
|
10
|
+
const instance = new MetaRouterAnalyticsClient(options);
|
|
11
|
+
await instance.init();
|
|
12
|
+
// 2) Wrap the real instance with the public interface
|
|
13
|
+
// Note: reset() also detaches the proxy so you’re "off" until you call createAnalyticsClient() again.
|
|
14
|
+
const boundClient = {
|
|
15
|
+
track: (event, props) => instance.track(event, props),
|
|
16
|
+
identify: (userId, traits) => instance.identify(userId, traits),
|
|
17
|
+
group: (groupId, traits) => instance.group(groupId, traits),
|
|
18
|
+
screen: (name, props) => instance.screen(name, props),
|
|
19
|
+
page: (name, props) => instance.page(name, props),
|
|
20
|
+
alias: (newUserId) => instance.alias(newUserId),
|
|
21
|
+
enableDebugLogging: () => instance.enableDebugLogging(),
|
|
22
|
+
getDebugInfo: () => instance.getDebugInfo(),
|
|
23
|
+
flush: () => instance.flush(),
|
|
24
|
+
// Detach the proxy after a successful reset so nothing leaks out
|
|
25
|
+
reset: async () => {
|
|
26
|
+
await instance.reset();
|
|
27
|
+
setRealClient(null, { dropPending: true }); // proxy goes idle; calls will queue or no-op
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
// 3) Bind the proxy to this fully-initialized client
|
|
31
|
+
setRealClient(boundClient);
|
|
32
|
+
// 4) Return the proxy as the single public handle
|
|
33
|
+
return proxyClient;
|
|
34
|
+
})();
|
|
35
|
+
try {
|
|
36
|
+
return await inFlight;
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
inFlight = null;
|
|
29
40
|
}
|
|
30
|
-
return analyticsInterface;
|
|
31
41
|
}
|
|
@@ -1,17 +1,6 @@
|
|
|
1
1
|
import type { AnalyticsInterface } from "../types";
|
|
2
|
-
/**
|
|
3
|
-
* proxyClient implements a proxy pattern for the AnalyticsInterface.
|
|
4
|
-
*
|
|
5
|
-
* It allows analytics method calls (track, identify, etc.) to be made before the real analytics client
|
|
6
|
-
* is fully initialized. Calls are queued and replayed once the real client is set via setRealClient.
|
|
7
|
-
* This ensures that analytics events are not lost if called early in the app lifecycle.
|
|
8
|
-
*
|
|
9
|
-
* The proxy also provides a fallback for getDebugInfo, returning proxy state if the real client is not ready.
|
|
10
|
-
*
|
|
11
|
-
* Usage:
|
|
12
|
-
* - Use proxyClient as the default analytics client before initialization.
|
|
13
|
-
* - Call setRealClient(realClientInstance) once the real client is ready.
|
|
14
|
-
*/
|
|
15
2
|
export declare const proxyClient: AnalyticsInterface;
|
|
16
|
-
export declare function setRealClient(client: AnalyticsInterface | null
|
|
3
|
+
export declare function setRealClient(client: AnalyticsInterface | null, opts?: {
|
|
4
|
+
dropPending?: boolean;
|
|
5
|
+
}): void;
|
|
17
6
|
//# sourceMappingURL=proxyClient.d.ts.map
|
|
@@ -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;AAqGnD,eAAO,MAAM,WAAW,EAAE,kBAYzB,CAAC;AAEF,wBAAgB,aAAa,CAC3B,MAAM,EAAE,kBAAkB,GAAG,IAAI,EACjC,IAAI,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,OAAO,CAAA;CAAE,QAgBjC"}
|
|
@@ -1,34 +1,80 @@
|
|
|
1
1
|
const pendingCalls = [];
|
|
2
2
|
const MAX_PENDING_CALLS = 20;
|
|
3
3
|
let realClient = null;
|
|
4
|
+
// Async-returning methods
|
|
5
|
+
const ASYNC_METHODS = {
|
|
6
|
+
flush: true,
|
|
7
|
+
reset: true,
|
|
8
|
+
getDebugInfo: true,
|
|
9
|
+
};
|
|
10
|
+
// One in-flight flush at a time
|
|
11
|
+
let flushInFlight = null;
|
|
4
12
|
function handleMethodCall(methodName, ...args) {
|
|
13
|
+
// Real client bound
|
|
5
14
|
if (realClient) {
|
|
15
|
+
if (methodName === "flush") {
|
|
16
|
+
if (flushInFlight)
|
|
17
|
+
return flushInFlight;
|
|
18
|
+
const p = Promise.resolve(realClient.flush(...args)).then(() => undefined);
|
|
19
|
+
flushInFlight = p.finally(() => {
|
|
20
|
+
flushInFlight = null;
|
|
21
|
+
});
|
|
22
|
+
return flushInFlight;
|
|
23
|
+
}
|
|
6
24
|
return realClient[methodName](...args);
|
|
7
25
|
}
|
|
26
|
+
// No real client bound yet
|
|
8
27
|
if (pendingCalls.length >= MAX_PENDING_CALLS) {
|
|
9
|
-
// Drop the oldest call
|
|
10
28
|
pendingCalls.shift();
|
|
11
29
|
console.warn(`[MetaRouter] Proxy queue reached max size (${MAX_PENDING_CALLS}). Oldest call dropped.`);
|
|
12
30
|
}
|
|
31
|
+
// Special-cases while unbound:
|
|
32
|
+
if (methodName === "getDebugInfo") {
|
|
33
|
+
// Return immediate proxy snapshot instead of queueing
|
|
34
|
+
return Promise.resolve({
|
|
35
|
+
proxy: true,
|
|
36
|
+
pendingCalls: pendingCalls.length,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
if (methodName === "reset") {
|
|
40
|
+
// Nothing to reset pre-bind; resolve immediately
|
|
41
|
+
return Promise.resolve();
|
|
42
|
+
}
|
|
43
|
+
if (ASYNC_METHODS[String(methodName)]) {
|
|
44
|
+
// Queue async call and return a promise that resolves after bind+run
|
|
45
|
+
return new Promise((resolve, reject) => {
|
|
46
|
+
pendingCalls.push(async () => {
|
|
47
|
+
try {
|
|
48
|
+
if (!realClient)
|
|
49
|
+
return reject(new Error("Proxy detached before real client was bound"));
|
|
50
|
+
if (methodName === "flush") {
|
|
51
|
+
if (!flushInFlight) {
|
|
52
|
+
const p = Promise.resolve(realClient.flush(...args)).then(() => undefined);
|
|
53
|
+
flushInFlight = p.finally(() => {
|
|
54
|
+
flushInFlight = null;
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
return flushInFlight.then(resolve, reject);
|
|
58
|
+
}
|
|
59
|
+
const result = realClient[methodName](...args);
|
|
60
|
+
result instanceof Promise
|
|
61
|
+
? result.then(resolve, reject)
|
|
62
|
+
: resolve(result);
|
|
63
|
+
}
|
|
64
|
+
catch (err) {
|
|
65
|
+
reject(err);
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
// Fire-and-forget: queue and return void
|
|
13
71
|
pendingCalls.push(() => {
|
|
14
|
-
if (realClient)
|
|
15
|
-
|
|
16
|
-
|
|
72
|
+
if (!realClient)
|
|
73
|
+
return;
|
|
74
|
+
realClient[methodName](...args);
|
|
17
75
|
});
|
|
76
|
+
return undefined;
|
|
18
77
|
}
|
|
19
|
-
/**
|
|
20
|
-
* proxyClient implements a proxy pattern for the AnalyticsInterface.
|
|
21
|
-
*
|
|
22
|
-
* It allows analytics method calls (track, identify, etc.) to be made before the real analytics client
|
|
23
|
-
* is fully initialized. Calls are queued and replayed once the real client is set via setRealClient.
|
|
24
|
-
* This ensures that analytics events are not lost if called early in the app lifecycle.
|
|
25
|
-
*
|
|
26
|
-
* The proxy also provides a fallback for getDebugInfo, returning proxy state if the real client is not ready.
|
|
27
|
-
*
|
|
28
|
-
* Usage:
|
|
29
|
-
* - Use proxyClient as the default analytics client before initialization.
|
|
30
|
-
* - Call setRealClient(realClientInstance) once the real client is ready.
|
|
31
|
-
*/
|
|
32
78
|
export const proxyClient = {
|
|
33
79
|
track: (event, props) => handleMethodCall("track", event, props),
|
|
34
80
|
identify: (userId, traits) => handleMethodCall("identify", userId, traits),
|
|
@@ -39,18 +85,24 @@ export const proxyClient = {
|
|
|
39
85
|
flush: () => handleMethodCall("flush"),
|
|
40
86
|
reset: () => handleMethodCall("reset"),
|
|
41
87
|
enableDebugLogging: () => handleMethodCall("enableDebugLogging"),
|
|
42
|
-
getDebugInfo: () =>
|
|
43
|
-
var _a, _b;
|
|
44
|
-
return (_b = (_a = realClient === null || realClient === void 0 ? void 0 : realClient.getDebugInfo) === null || _a === void 0 ? void 0 : _a.call(realClient)) !== null && _b !== void 0 ? _b : {
|
|
45
|
-
proxy: true,
|
|
46
|
-
pendingCalls: pendingCalls.length,
|
|
47
|
-
};
|
|
48
|
-
},
|
|
88
|
+
getDebugInfo: () => handleMethodCall("getDebugInfo"),
|
|
49
89
|
};
|
|
50
|
-
export function setRealClient(client) {
|
|
90
|
+
export function setRealClient(client, opts) {
|
|
51
91
|
realClient = client;
|
|
52
92
|
if (client) {
|
|
53
|
-
pendingCalls.
|
|
54
|
-
|
|
93
|
+
const fns = pendingCalls.splice(0, pendingCalls.length);
|
|
94
|
+
for (const fn of fns) {
|
|
95
|
+
try {
|
|
96
|
+
const r = fn();
|
|
97
|
+
if (r instanceof Promise)
|
|
98
|
+
r.catch(() => { });
|
|
99
|
+
}
|
|
100
|
+
catch { }
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
if (opts === null || opts === void 0 ? void 0 : opts.dropPending)
|
|
105
|
+
pendingCalls.length = 0;
|
|
106
|
+
flushInFlight = null; // reset coalescer
|
|
55
107
|
}
|
|
56
108
|
}
|
package/lib/analytics/types.d.ts
CHANGED
|
@@ -30,10 +30,10 @@ export interface AnalyticsInterface {
|
|
|
30
30
|
screen: (name: string, props?: Record<string, any>) => void;
|
|
31
31
|
page: (name: string, props?: Record<string, any>) => void;
|
|
32
32
|
alias: (newUserId: string) => void;
|
|
33
|
-
flush: () => void
|
|
34
|
-
reset: () => void
|
|
33
|
+
flush: () => Promise<void>;
|
|
34
|
+
reset: () => Promise<void>;
|
|
35
35
|
enableDebugLogging: () => void;
|
|
36
|
-
getDebugInfo: () => Record<string, any
|
|
36
|
+
getDebugInfo: () => Promise<Record<string, any>>;
|
|
37
37
|
}
|
|
38
38
|
export interface EventContext {
|
|
39
39
|
app: {
|
|
@@ -68,4 +68,5 @@ export interface EventContext {
|
|
|
68
68
|
timezone: string;
|
|
69
69
|
[key: string]: any;
|
|
70
70
|
}
|
|
71
|
+
export type Lifecycle = "idle" | "initializing" | "ready" | "resetting" | "disabled";
|
|
71
72
|
//# sourceMappingURL=types.d.ts.map
|
|
@@ -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,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC7B,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACjC,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,iBAAkB,SAAQ,YAAY;IACrD,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,oBAAqB,SAAQ,iBAAiB;IAC7D,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,YAAY,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;IACtB,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,kBA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IAAI,CAAC;IAC/B,YAAY,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;CAClD;AAED,MAAM,WAAW,YAAY;IAC3B,GAAG,EAAE;QACH,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;QAChB,KAAK,EAAE,MAAM,CAAC;QACd,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;IACF,MAAM,EAAE;QACN,YAAY,EAAE,MAAM,CAAC;QACrB,KAAK,EAAE,MAAM,CAAC;QACd,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;KACd,CAAC;IACF,OAAO,EAAE;QACP,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;KACjB,CAAC;IACF,EAAE,EAAE;QACF,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;KACjB,CAAC;IACF,MAAM,EAAE;QACN,OAAO,EAAE,MAAM,CAAC;QAChB,KAAK,EAAE,MAAM,CAAC;QACd,MAAM,EAAE,MAAM,CAAC;KAChB,CAAC;IACF,OAAO,EAAE;QACP,IAAI,EAAE,OAAO,CAAC;KACf,CAAC;IACF,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAED,MAAM,MAAM,SAAS,GACjB,MAAM,GACN,cAAc,GACd,OAAO,GACP,WAAW,GACX,UAAU,CAAC"}
|
|
@@ -1,16 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
* @template T The return type of the async function.
|
|
9
|
-
* @param fn The asynchronous function to retry.
|
|
10
|
-
* @param retries The maximum number of attempts (default: 5).
|
|
11
|
-
* @param baseDelayMs The base delay in milliseconds for backoff (default: 1000).
|
|
12
|
-
* @param sleep Optional custom sleep function (default: setTimeout-based Promise).
|
|
13
|
-
* @returns A promise that resolves with the result of `fn`, or rejects after all retries fail.
|
|
14
|
-
*/
|
|
15
|
-
export declare function retryWithBackoff<T>(fn: () => Promise<T>, retries?: number, baseDelayMs?: number, sleep?: (ms: number) => Promise<unknown>): Promise<T>;
|
|
1
|
+
export type BackoffOptions = {
|
|
2
|
+
retries?: number;
|
|
3
|
+
baseDelayMs?: number;
|
|
4
|
+
sleep?: (ms: number) => Promise<void>;
|
|
5
|
+
shouldContinue?: () => boolean;
|
|
6
|
+
};
|
|
7
|
+
export declare function retryWithBackoff<T>(fn: () => Promise<T>, opts?: BackoffOptions): Promise<T>;
|
|
16
8
|
//# sourceMappingURL=retry.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/retry.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/retry.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,cAAc,GAAG;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACtC,cAAc,CAAC,EAAE,MAAM,OAAO,CAAC;CAChC,CAAC;AAEF,wBAAsB,gBAAgB,CAAC,CAAC,EACtC,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACpB,IAAI,GAAE,cAAmB,GACxB,OAAO,CAAC,CAAC,CAAC,CA4BZ"}
|
|
@@ -1,20 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
*
|
|
4
|
-
* - Attempts to execute the provided async function up to `retries` times.
|
|
5
|
-
* - Waits an exponentially increasing delay (with random jitter) between attempts.
|
|
6
|
-
* - If all attempts fail, the last error is thrown.
|
|
7
|
-
*
|
|
8
|
-
* @template T The return type of the async function.
|
|
9
|
-
* @param fn The asynchronous function to retry.
|
|
10
|
-
* @param retries The maximum number of attempts (default: 5).
|
|
11
|
-
* @param baseDelayMs The base delay in milliseconds for backoff (default: 1000).
|
|
12
|
-
* @param sleep Optional custom sleep function (default: setTimeout-based Promise).
|
|
13
|
-
* @returns A promise that resolves with the result of `fn`, or rejects after all retries fail.
|
|
14
|
-
*/
|
|
15
|
-
export async function retryWithBackoff(fn, retries = 5, baseDelayMs = 1000, sleep = (ms) => new Promise((res) => setTimeout(res, ms))) {
|
|
1
|
+
export async function retryWithBackoff(fn, opts = {}) {
|
|
2
|
+
const { retries = 5, baseDelayMs = 1000, sleep = (ms) => new Promise((res) => setTimeout(res, ms)), shouldContinue = () => true, } = opts;
|
|
16
3
|
let attempt = 0;
|
|
17
4
|
while (attempt < retries) {
|
|
5
|
+
if (!shouldContinue())
|
|
6
|
+
throw new Error("Retry aborted by shouldContinue");
|
|
18
7
|
try {
|
|
19
8
|
return await fn();
|
|
20
9
|
}
|
|
@@ -25,7 +14,10 @@ export async function retryWithBackoff(fn, retries = 5, baseDelayMs = 1000, slee
|
|
|
25
14
|
const jitter = Math.random() * 100;
|
|
26
15
|
const delay = baseDelayMs * 2 ** (attempt - 1) + jitter;
|
|
27
16
|
await sleep(delay);
|
|
17
|
+
if (!shouldContinue())
|
|
18
|
+
throw new Error("Retry aborted by shouldContinue");
|
|
28
19
|
}
|
|
29
20
|
}
|
|
30
|
-
|
|
21
|
+
// Unreachable, but TS likes a return/throw
|
|
22
|
+
throw new Error("Exhausted all retries");
|
|
31
23
|
}
|