@metarouter/react-native-sdk 1.1.7 → 1.2.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 CHANGED
@@ -88,10 +88,10 @@ const MyComponent = () => {
88
88
  ```js
89
89
  import { createAnalyticsClient } from "@metarouter/react-native-sdk";
90
90
 
91
- // Initialize
91
+ // Initialize optionally await it but can use at anytime with events transmitted when client is available.
92
92
  const analytics = await createAnalyticsClient({
93
93
  writeKey: "your-write-key",
94
- ingestionHost: "https://your-ingestion-endpoint.com/events",
94
+ ingestionHost: "https://your-ingestion-endpoint.com",
95
95
  });
96
96
 
97
97
  // Track events
@@ -128,11 +128,11 @@ await analytics.reset();
128
128
 
129
129
  ### createAnalyticsClient(options)
130
130
 
131
- Initializes the analytics client and returns a promise resolving to the client instance.
131
+ Initializes the analytics client and returns a **live proxy** to the client instance.
132
132
 
133
- ⚠️ createAnalyticsClient() is asynchronous, but you do not need to await it before using analytics methods.
133
+ ⚠️ `createAnalyticsClient()` is asynchronous, but you **do not** need to `await` it before using analytics methods.
134
134
 
135
- Calls to track, identify, etc. are queued and replayed once the client is fully initialized.
135
+ Calls to `track`, `identify`, etc. are **buffered in-memory** by the proxy and replayed **in order** once the client is fully initialized.
136
136
 
137
137
  **Options:**
138
138
 
@@ -140,6 +140,14 @@ Calls to track, identify, etc. are queued and replayed once the client is fully
140
140
  - `ingestionHost` (string, required): Your MetaRouter ingestor host
141
141
  - `debug` (boolean, optional): Enable debug mode
142
142
  - `flushIntervalSeconds` (number, optional): Interval in seconds to flush events
143
+ - `maxQueueEvents` (number, optional): number of max events stored in memory
144
+
145
+ **Proxy behavior (quick notes):**
146
+
147
+ - Buffer is **in-memory only** (not persisted). Calls made before ready are lost if the process exits.
148
+ - Ordering is preserved relative to other buffered calls; normal FIFO + batching applies after ready.
149
+ - On fatal config errors (`401/403/404`), the client enters **disabled** state and drops subsequent calls.
150
+ - `sentAt` is stamped when the batch is prepared for transmission (just before network send). If you need the original occurrence time, pass your own `timestamp` on each event.
143
151
 
144
152
  ### Analytics Interface
145
153
 
@@ -205,7 +213,7 @@ analytics.enableDebugLogging?.();
205
213
 
206
214
  ```js
207
215
  // Get current state information
208
- const debugInfo = analytics.getDebugInfo?.();
216
+ const debugInfo = await analytics.getDebugInfo?.();
209
217
  console.log("Analytics debug info:", debugInfo);
210
218
  ```
211
219
 
@@ -223,6 +231,41 @@ await analytics.flush();
223
231
  - **Endpoint URL**: Verify your ingestion endpoint is correct and accessible
224
232
  - **Write Key**: Ensure your write key is valid
225
233
 
234
+ ### Delivery & Backoff (How events flow under failures)
235
+
236
+ Queue capacity: The SDK keeps up to 2,000 events in memory. When the cap is reached, the oldest events are dropped first (drop-oldest). You can change this via maxQueueEvents in createAnalyticsClient(options)
237
+
238
+ This SDK uses a circuit breaker around network I/O. It keeps ordering stable, avoids tight retry loops, and backs off cleanly when your cluster is unhealthy or throttling.
239
+
240
+ Queueing during backoff: While the breaker is OPEN, new events are accepted and appended to the in-memory queue; nothing is sent until the cooldown elapses.
241
+
242
+ Ordering (FIFO): If a batch fails with a retryable error, that batch is requeued at the front (original order preserved). New events go to the tail. After cooldown, we try again; on success we continue draining in order.
243
+
244
+ Half-open probe: After cooldown, one probe is allowed.
245
+ Success → breaker CLOSED (keep flushing).
246
+ Failure → breaker OPEN again with longer cooldown.
247
+
248
+ sentAt semantics: sentAt is stamped when the event is enqueued. If the client is backing off, the actual transmit may be later; sentAt reflects when the event entered the queue.
249
+
250
+ | Status / Failure | Action | Breaker | Queue effect |
251
+ | ----------------------------------- | -------------------------------------------------------------------- | ------- | ------------------------------ |
252
+ | `2xx` | Success | close | Batch removed |
253
+ | `5xx` | Retry: requeue **front**, schedule after cooldown | open↑ | Requeued (front) |
254
+ | `408` (timeout) | Retry: requeue **front**, schedule after cooldown | open↑ | Requeued (front) |
255
+ | `429` (throttle) | Retry: requeue **front**, wait = `max(Retry-After, breaker, 1000ms)` | open↑ | Requeued (front) |
256
+ | `413` (payload too large) | Halve `maxBatchSize`; requeue and retry; if already `1`, **drop** | close | Requeued or dropped (`size=1`) |
257
+ | `400`, `422`, other non-fatal `4xx` | **Drop** bad batch, continue | close | Dropped |
258
+ | `401`, `403`, `404` | **Disable** client (stop timers), clear queue | close | Cleared |
259
+ | Network error / Abort / Timeout | Retry: requeue **front**, schedule after cooldown | open↑ | Requeued (front) |
260
+ | Reset during flush | Do **not** requeue in-flight chunk; **drop** it | — | Dropped |
261
+
262
+ **Defaults:** `failureThreshold=3`, `cooldownMs=10s`, `maxCooldownMs=120s`, `jitter=±20%`, `halfOpenMaxConcurrent=1`.
263
+
264
+ **Identifiers:**
265
+
266
+ - `anonymousId` is a stable, persisted UUID for the device/user before identify; it does **not** include timestamps.
267
+ - `messageId` is generated as `<epochMillis>-<uuid>` (e.g., `1734691572843-6f0c7e85-...`) to aid debugging.
268
+
226
269
  ## License
227
270
 
228
271
  MIT
@@ -233,4 +276,4 @@ MIT
233
276
 
234
277
  This library includes code from the following third-party packages:
235
278
 
236
- - [uuid](https://github.com/uuidjs/uuid), MIT License
279
+ - [react-native-uuid](https://github.com/eugenehp/react-native-uuid), MIT License
@@ -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;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
+ {"version":3,"file":"IdentityManager.d.ts","sourceRoot":"","sources":["../../src/analytics/IdentityManager.ts"],"names":[],"mappings":"AAEA,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;IAmC3B;;;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,4 +1,5 @@
1
1
  import { log, warn } from "./utils/logger";
2
+ import uuid from "react-native-uuid";
2
3
  import { USER_ID_KEY, GROUP_ID_KEY, ANONYMOUS_ID_KEY, getIdentityField, setIdentityField, removeIdentityField, } from "./utils/identityStorage";
3
4
  /**
4
5
  * Manages user, group, and anonymous identity for analytics events.
@@ -19,9 +20,7 @@ export class IdentityManager {
19
20
  try {
20
21
  const storedAnonId = await getIdentityField(ANONYMOUS_ID_KEY);
21
22
  if (!storedAnonId) {
22
- const newId = `anon-${Date.now()}-${Math.random()
23
- .toString(36)
24
- .substring(2, 10)}`;
23
+ const newId = uuid.v4();
25
24
  await setIdentityField(ANONYMOUS_ID_KEY, newId);
26
25
  this.anonymousId = newId;
27
26
  log("Generated and stored new anonymous ID:", newId);
@@ -20,7 +20,11 @@ export declare class MetaRouterAnalyticsClient {
20
20
  private identityManager;
21
21
  private static readonly MAX_QUEUE_SIZE;
22
22
  private flushInFlight;
23
- private readonly MAX_BATCH_SIZE;
23
+ private maxBatchSize;
24
+ private circuit;
25
+ private nextTimer;
26
+ private nextScheduledAt;
27
+ private maxQueueEvents;
24
28
  /**
25
29
  * Initializes the analytics client with the provided options.
26
30
  * @param options - The initialization options.
@@ -31,15 +35,13 @@ export declare class MetaRouterAnalyticsClient {
31
35
  * @returns A promise that resolves when the client is initialized.
32
36
  */
33
37
  init(): Promise<void>;
38
+ private endpoint;
34
39
  /**
35
40
  * Starts the flush loop.
36
41
  */
37
42
  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
+ private isReady;
44
+ private makeBreaker;
43
45
  /**
44
46
  * Fetches with a timeout.
45
47
  * @param url - The URL to fetch.
@@ -58,6 +60,11 @@ export declare class MetaRouterAnalyticsClient {
58
60
  * @param event - The event to enqueue.
59
61
  */
60
62
  private enqueue;
63
+ private drainBatch;
64
+ private scheduleFlushIn;
65
+ private stopFlushLoop;
66
+ private clearNextTimer;
67
+ private parseRetryAfter;
61
68
  /**
62
69
  * Sets up the app state listener.
63
70
  */
@@ -120,9 +127,14 @@ export declare class MetaRouterAnalyticsClient {
120
127
  userId: string | undefined;
121
128
  groupId: string | undefined;
122
129
  proxy: boolean;
130
+ flushInFlight: boolean;
131
+ circuitState: import("./utils/circuitBreaker").CircuitState;
132
+ circuitRemainingMs: number;
133
+ maxQueueEvents: number;
123
134
  }>;
124
135
  /**
125
- * Flushes the event queue to the ingestion endpoint.
136
+ * Flushes the event queue to the ingestion endpoint in chunks.
137
+ * Singleflight: coalesces concurrent callers.
126
138
  */
127
139
  flush(): Promise<void>;
128
140
  /**
@@ -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;AAQ7E;;;;;;GAMG;AACH,qBAAa,yBAAyB;IACpC,OAAO,CAAC,SAAS,CAAqB;IACtC,OAAO,CAAC,WAAW,CAA8B;IACjD,OAAO,CAAC,KAAK,CAAsB;IACnC,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,UAAU,CAA+B;IACjD,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,CAAC,aAAa,CAA8B;IACnD,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAO;IAEtC;;;OAGG;gBACS,OAAO,EAAE,WAAW;IAkChC;;;OAGG;IACU,IAAI;IA2CjB;;OAEG;IACH,OAAO,CAAC,cAAc;IAItB;;;OAGG;IACH,OAAO,CAAC,UAAU;IAIlB;;;;;;OAMG;YACW,gBAAgB;IAgC9B;;;OAGG;IACH,OAAO,CAAC,GAAG;IAIX;;;OAGG;IACH,OAAO,CAAC,OAAO;IAuBf;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAO7B;;;OAGG;IACH,OAAO,CAAC,oBAAoB,CAK1B;IAEF;;;;OAIG;IACH,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,E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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;;;;;;;;;;;;;;;IAmBlB;;;OAGG;IACG,KAAK;IA2JX;;OAEG;IACU,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CA6BpC"}
@@ -1,9 +1,9 @@
1
1
  import { AppState } from "react-native";
2
- import { retryWithBackoff } from "./utils/retry";
3
- import { error, log, setDebugLogging, warn } from "./utils/logger";
2
+ import { log, setDebugLogging, warn, error } from "./utils/logger";
4
3
  import { IdentityManager } from "./IdentityManager";
5
4
  import { enrichEvent } from "./utils/enrichEvent";
6
5
  import { getContextInfo } from "./utils/contextInfo";
6
+ import CircuitBreaker from "./utils/circuitBreaker";
7
7
  /**
8
8
  * Analytics client for MetaRouter.
9
9
  * - Handles event queueing, batching, and delivery with retries.
@@ -17,7 +17,7 @@ export class MetaRouterAnalyticsClient {
17
17
  * @param options - The initialization options.
18
18
  */
19
19
  constructor(options) {
20
- var _a;
20
+ var _a, _b;
21
21
  this.lifecycle = "idle";
22
22
  this.initPromise = null;
23
23
  this.queue = [];
@@ -26,13 +26,21 @@ export class MetaRouterAnalyticsClient {
26
26
  this.appState = AppState.currentState;
27
27
  this.appStateSubscription = null;
28
28
  this.flushInFlight = null;
29
- this.MAX_BATCH_SIZE = 100;
29
+ this.maxBatchSize = 100;
30
+ this.nextTimer = null;
31
+ this.nextScheduledAt = null;
30
32
  /**
31
33
  * Handles the app state change event.
32
34
  * @param nextState - The new app state.
33
35
  */
34
36
  this.handleAppStateChange = (nextState) => {
35
37
  if (this.appState === "active" && nextState.match(/inactive|background/)) {
38
+ this.flush(); // try to get events out
39
+ this.stopFlushLoop(); // pause periodic loop
40
+ this.clearNextTimer(); // cancel probe timer
41
+ }
42
+ if (nextState === "active" && this.lifecycle === "ready") {
43
+ this.startFlushLoop(); // resume periodic loop
36
44
  this.flush();
37
45
  }
38
46
  this.appState = nextState;
@@ -43,8 +51,13 @@ export class MetaRouterAnalyticsClient {
43
51
  throw new Error("MetaRouterAnalyticsClient initialization failed: `writeKey` is required and must be a non-empty string.");
44
52
  }
45
53
  try {
46
- const url = new URL(ingestionHost);
47
- if (url.pathname !== "/" && ingestionHost.endsWith("/")) {
54
+ // Validate it's a proper absolute URL
55
+ // and ensure it does not end with a trailing slash
56
+ // e.g., "https://example.com" or "https://example.com/api" are valid,
57
+ // but "https://example.com/" or "https://example.com/api/" are not.
58
+ // eslint-disable-next-line no-new
59
+ new URL(ingestionHost);
60
+ if (ingestionHost.endsWith("/")) {
48
61
  throw new Error();
49
62
  }
50
63
  }
@@ -58,6 +71,8 @@ export class MetaRouterAnalyticsClient {
58
71
  : 10000;
59
72
  setDebugLogging((_a = options.debug) !== null && _a !== void 0 ? _a : false);
60
73
  this.identityManager = new IdentityManager();
74
+ this.circuit = this.makeBreaker();
75
+ this.maxQueueEvents = (_b = options.maxQueueEvents) !== null && _b !== void 0 ? _b : 2000;
61
76
  log("Analytics client constructor completed, initialization in progress...");
62
77
  }
63
78
  /**
@@ -99,19 +114,33 @@ export class MetaRouterAnalyticsClient {
99
114
  })();
100
115
  return this.initPromise;
101
116
  }
117
+ endpoint(path) {
118
+ return `${this.ingestionHost}${path.startsWith("/") ? path : `/${path}`}`;
119
+ }
102
120
  /**
103
121
  * Starts the flush loop.
104
122
  */
105
123
  startFlushLoop() {
124
+ if (this.flushTimer)
125
+ clearInterval(this.flushTimer);
106
126
  this.flushTimer = setInterval(() => this.flush(), this.flushIntervalMs);
107
127
  }
108
- /**
109
- * Checks if the analytics client can operate.
110
- * @returns True if the client is ready to operate, false otherwise.
111
- */
112
- canOperate() {
128
+ isReady() {
113
129
  return this.lifecycle === "ready";
114
130
  }
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
+ }
115
144
  /**
116
145
  * Fetches with a timeout.
117
146
  * @param url - The URL to fetch.
@@ -120,30 +149,15 @@ export class MetaRouterAnalyticsClient {
120
149
  * @returns The response.
121
150
  */
122
151
  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
- });
152
+ const ctrl = new AbortController();
153
+ const to = setTimeout(() => ctrl.abort(), timeoutMs);
154
+ try {
155
+ const res = await fetch(url, { ...init, signal: ctrl.signal });
156
+ return res;
157
+ }
158
+ finally {
159
+ clearTimeout(to);
160
+ }
147
161
  }
148
162
  /**
149
163
  * Returns the current timestamp in ISO format.
@@ -157,18 +171,70 @@ export class MetaRouterAnalyticsClient {
157
171
  * @param event - The event to enqueue.
158
172
  */
159
173
  enqueue(event) {
160
- if (!this.canOperate()) {
174
+ if (!this.isReady()) {
161
175
  warn("Analytics client is not ready to operate");
162
176
  return;
163
177
  }
164
178
  const eventWithIdentity = this.identityManager.addIdentityInfo(event);
165
179
  const enrichedEvent = enrichEvent(eventWithIdentity, this.writeKey, this.context);
166
- log("Enqueuing event", enrichedEvent);
180
+ // ⬇️ hard cap: drop OLDEST until there's room
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
+ });
167
189
  this.queue.push(enrichedEvent);
168
190
  if (this.queue.length >= MetaRouterAnalyticsClient.MAX_QUEUE_SIZE) {
169
- log(`Event queue reached max size (${MetaRouterAnalyticsClient.MAX_QUEUE_SIZE}). Flushing queued events.`);
191
+ log(`Event queue reached ${MetaRouterAnalyticsClient.MAX_QUEUE_SIZE}. Flushing queued events.`);
192
+ this.flush();
193
+ }
194
+ }
195
+ drainBatch() {
196
+ const n = Math.min(this.queue.length, this.maxBatchSize);
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)
206
+ return;
207
+ // Otherwise, replace the existing timer with the earlier one.
208
+ if (this.nextTimer)
209
+ clearTimeout(this.nextTimer);
210
+ this.nextScheduledAt = target;
211
+ this.nextTimer = setTimeout(() => {
212
+ this.nextScheduledAt = null;
213
+ this.nextTimer = null;
170
214
  this.flush();
215
+ }, Math.max(0, ms));
216
+ }
217
+ stopFlushLoop() {
218
+ if (this.flushTimer) {
219
+ clearInterval(this.flushTimer);
220
+ this.flushTimer = null;
221
+ }
222
+ }
223
+ clearNextTimer() {
224
+ if (this.nextTimer) {
225
+ clearTimeout(this.nextTimer);
226
+ this.nextTimer = null;
171
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());
172
238
  }
173
239
  /**
174
240
  * Sets up the app state listener.
@@ -260,6 +326,7 @@ export class MetaRouterAnalyticsClient {
260
326
  * Get current state for debugging
261
327
  */
262
328
  async getDebugInfo() {
329
+ const state = this.circuit.getState();
263
330
  return {
264
331
  lifecycle: this.lifecycle,
265
332
  queueLength: this.queue.length,
@@ -270,64 +337,134 @@ export class MetaRouterAnalyticsClient {
270
337
  userId: this.identityManager.getUserId(),
271
338
  groupId: this.identityManager.getGroupId(),
272
339
  proxy: false,
340
+ flushInFlight: !!this.flushInFlight,
341
+ circuitState: state,
342
+ circuitRemainingMs: this.circuit.remainingCooldownMs(),
343
+ maxQueueEvents: this.maxQueueEvents,
273
344
  };
274
345
  }
275
346
  /**
276
- * Flushes the event queue to the ingestion endpoint.
347
+ * Flushes the event queue to the ingestion endpoint in chunks.
348
+ * Singleflight: coalesces concurrent callers.
277
349
  */
278
350
  async flush() {
279
- if (!this.canOperate())
280
- return;
281
351
  if (!this.queue.length)
282
352
  return;
283
353
  if (this.flushInFlight)
284
- return this.flushInFlight; // coalesce
354
+ return this.flushInFlight;
355
+ if (!this.isReady())
356
+ return;
285
357
  const anonId = this.identityManager.getAnonymousId();
286
358
  if (!anonId) {
287
359
  warn("Anonymous ID not yet ready, delaying flush");
288
360
  return;
289
361
  }
290
- const batch = this.queue.map((e) => ({
291
- ...e,
292
- sentAt: new Date().toISOString(),
293
- }));
294
- this.queue = []; // optimistic clear; we’ll put them back on failure
295
362
  const doFlush = async () => {
296
- await retryWithBackoff(async () => {
297
- if (!this.canOperate())
298
- throw new Error("Client not ready during flush");
299
- log("Making API call to:", this.ingestionHost + "/v1/batch");
300
- const response = await this.fetchWithTimeout(this.ingestionHost + "/v1/batch", {
301
- method: "POST",
302
- headers: { "Content-Type": "application/json" },
303
- body: JSON.stringify({ batch }),
304
- }, 8000 // timeout per attempt
305
- );
306
- if (!response.ok) {
307
- error("HTTP error", response.status, response.statusText);
308
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
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
309
449
  }
310
- log("API call successful, status:", response.status);
311
- }, {
312
- retries: 5,
313
- baseDelayMs: 1000,
314
- shouldContinue: () => this.canOperate(),
315
- });
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
+ }
316
465
  log("Flush completed successfully");
317
466
  };
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(() => {
467
+ this.flushInFlight = doFlush().finally(() => {
331
468
  this.flushInFlight = null;
332
469
  });
333
470
  return this.flushInFlight;
@@ -347,14 +484,15 @@ export class MetaRouterAnalyticsClient {
347
484
  }
348
485
  (_b = (_a = this.appStateSubscription) === null || _a === void 0 ? void 0 : _a.remove) === null || _b === void 0 ? void 0 : _b.call(_a);
349
486
  this.appStateSubscription = null;
350
- // Drop queued events
351
487
  this.queue = [];
488
+ this.circuit = this.makeBreaker();
352
489
  // Clear identity (must remove persisted IDs)
353
490
  await this.identityManager.reset();
354
491
  // Allow a clean future init
355
492
  this.initPromise = null;
356
493
  // Back to idle: explicit init required
357
494
  this.lifecycle = "idle";
495
+ this.clearNextTimer();
358
496
  log("Analytics client reset complete");
359
497
  }
360
498
  }
@@ -1,5 +1,32 @@
1
1
  import type { AnalyticsInterface } from "../types";
2
2
  export declare const proxyClient: AnalyticsInterface;
3
+ /**
4
+ * Binds or unbinds the real analytics client to the proxy and manages queued calls.
5
+ *
6
+ * - **Binding (`client` is non-null):**
7
+ * - Sets `realClient` to `client`.
8
+ * - Drains `pendingCalls` FIFO and replays each thunk against the bound client.
9
+ * Replay errors are swallowed (logged) to avoid crashing callers that already returned.
10
+ * If a thunk returns a Promise, its rejection is caught to prevent unhandled rejections.
11
+ *
12
+ * - **Unbinding (`client` is null):**
13
+ * - If `opts.dropPending` is true:
14
+ * - Rejects any queued async calls using their stored `reject` handlers
15
+ * with an explanatory error.
16
+ * - Empties the `pendingCalls` queue.
17
+ * - Resets `flushInFlight` so subsequent `flush()` calls can start a new singleflight.
18
+ *
19
+ * **Notes:**
20
+ * - Replay is non-reentrant for the current batch: thunks enqueued during replay
21
+ * are not executed until a future bind/drain cycle (prevents infinite loops).
22
+ * - This function does not start initialization; callers are expected to call
23
+ * `setRealClient(real)` once the real client is ready, and `setRealClient(null, { dropPending: true })`
24
+ * on reset/teardown to ensure pre-bind Promises don’t hang indefinitely.
25
+ *
26
+ * @param client - The concrete analytics client to bind, or `null` to unbind.
27
+ * @param opts - Options for unbinding behavior.
28
+ * @param opts.dropPending - When unbinding, reject and clear any queued pre-bind async calls.
29
+ */
3
30
  export declare function setRealClient(client: AnalyticsInterface | null, opts?: {
4
31
  dropPending?: boolean;
5
32
  }): void;
@@ -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;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
+ {"version":3,"file":"proxyClient.d.ts","sourceRoot":"","sources":["../../../src/analytics/proxy/proxyClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AA4InD,eAAO,MAAM,WAAW,EAAE,kBAYzB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,kBAAkB,GAAG,IAAI,EACjC,IAAI,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,OAAO,CAAA;CAAE,QAqBjC"}
@@ -1,15 +1,39 @@
1
1
  const pendingCalls = [];
2
2
  const MAX_PENDING_CALLS = 20;
3
3
  let realClient = null;
4
- // Async-returning methods
5
4
  const ASYNC_METHODS = {
6
5
  flush: true,
7
- reset: true,
8
6
  getDebugInfo: true,
9
7
  };
8
+ const isAsyncMethod = (m) => ASYNC_METHODS[m] === true;
10
9
  // One in-flight flush at a time
11
10
  let flushInFlight = null;
11
+ /**
12
+ * Dispatches a method call to the underlying analytics client, handling both
13
+ * pre-bind (proxy) and post-bind (real client) states.
14
+ *
15
+ * - **Post-bind:**
16
+ * Calls the method directly on the bound `realClient`.
17
+ * - For `flush()`, enforces a singleflight: concurrent calls return the same
18
+ * in-flight Promise and no duplicate flush is triggered.
19
+ *
20
+ * - **Pre-bind:**
21
+ * - Queues the call in `pendingCalls` for replay after binding.
22
+ * - For async methods (`flush`, `reset`, `getDebugInfo`), returns a Promise
23
+ * that resolves/rejects after replay. Keeps a `reject` handle so
24
+ * `dropPending` can fail them immediately.
25
+ * - For sync "fire-and-forget" methods, returns `void` immediately.
26
+ * - For `getDebugInfo`, returns an immediate proxy snapshot without queuing.
27
+ * - For `reset`, returns an immediate resolved Promise (no-op).
28
+ * - If the queue exceeds `MAX_PENDING_CALLS`, drops the oldest call
29
+ * (rejecting it if async) and logs a warning.
30
+ *
31
+ * @param methodName - Name of the `AnalyticsInterface` method to invoke.
32
+ * @param args - Arguments to pass to the method.
33
+ * @returns The method's return value or a queued Promise, depending on binding state.
34
+ */
12
35
  function handleMethodCall(methodName, ...args) {
36
+ var _a;
13
37
  // Real client bound
14
38
  if (realClient) {
15
39
  if (methodName === "flush") {
@@ -25,8 +49,9 @@ function handleMethodCall(methodName, ...args) {
25
49
  }
26
50
  // No real client bound yet
27
51
  if (pendingCalls.length >= MAX_PENDING_CALLS) {
28
- pendingCalls.shift();
29
- console.warn(`[MetaRouter] Proxy queue reached max size (${MAX_PENDING_CALLS}). Oldest call dropped.`);
52
+ const dropped = pendingCalls.shift();
53
+ (_a = dropped === null || dropped === void 0 ? void 0 : dropped.reject) === null || _a === void 0 ? void 0 : _a.call(dropped, new Error(`[MetaRouter] Dropped oldest call (queue cap ${MAX_PENDING_CALLS})`));
54
+ console.warn(`[MetaRouter] Oldest call dropped (queue cap ${MAX_PENDING_CALLS})`);
30
55
  }
31
56
  // Special-cases while unbound:
32
57
  if (methodName === "getDebugInfo") {
@@ -40,38 +65,42 @@ function handleMethodCall(methodName, ...args) {
40
65
  // Nothing to reset pre-bind; resolve immediately
41
66
  return Promise.resolve();
42
67
  }
43
- if (ASYNC_METHODS[String(methodName)]) {
68
+ if (isAsyncMethod(methodName)) {
44
69
  // Queue async call and return a promise that resolves after bind+run
45
70
  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
- });
71
+ pendingCalls.push({
72
+ reject, // keep a handle for dropPending
73
+ fn: async () => {
74
+ try {
75
+ if (!realClient) {
76
+ return reject(new Error("Proxy detached before real client was bound"));
56
77
  }
57
- return flushInFlight.then(resolve, reject);
78
+ if (methodName === "flush") {
79
+ if (!flushInFlight) {
80
+ const p = Promise.resolve(realClient.flush(...args)).then(() => undefined);
81
+ flushInFlight = p.finally(() => {
82
+ flushInFlight = null;
83
+ });
84
+ }
85
+ return flushInFlight.then(resolve, reject);
86
+ }
87
+ const result = realClient[methodName](...args);
88
+ Promise.resolve(result).then(resolve, reject);
89
+ }
90
+ catch (err) {
91
+ reject(err);
58
92
  }
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
- }
93
+ },
67
94
  });
68
95
  });
69
96
  }
70
97
  // Fire-and-forget: queue and return void
71
- pendingCalls.push(() => {
72
- if (!realClient)
73
- return;
74
- realClient[methodName](...args);
98
+ pendingCalls.push({
99
+ fn: () => {
100
+ if (!realClient)
101
+ return;
102
+ realClient[methodName](...args);
103
+ },
75
104
  });
76
105
  return undefined;
77
106
  }
@@ -87,22 +116,53 @@ export const proxyClient = {
87
116
  enableDebugLogging: () => handleMethodCall("enableDebugLogging"),
88
117
  getDebugInfo: () => handleMethodCall("getDebugInfo"),
89
118
  };
119
+ /**
120
+ * Binds or unbinds the real analytics client to the proxy and manages queued calls.
121
+ *
122
+ * - **Binding (`client` is non-null):**
123
+ * - Sets `realClient` to `client`.
124
+ * - Drains `pendingCalls` FIFO and replays each thunk against the bound client.
125
+ * Replay errors are swallowed (logged) to avoid crashing callers that already returned.
126
+ * If a thunk returns a Promise, its rejection is caught to prevent unhandled rejections.
127
+ *
128
+ * - **Unbinding (`client` is null):**
129
+ * - If `opts.dropPending` is true:
130
+ * - Rejects any queued async calls using their stored `reject` handlers
131
+ * with an explanatory error.
132
+ * - Empties the `pendingCalls` queue.
133
+ * - Resets `flushInFlight` so subsequent `flush()` calls can start a new singleflight.
134
+ *
135
+ * **Notes:**
136
+ * - Replay is non-reentrant for the current batch: thunks enqueued during replay
137
+ * are not executed until a future bind/drain cycle (prevents infinite loops).
138
+ * - This function does not start initialization; callers are expected to call
139
+ * `setRealClient(real)` once the real client is ready, and `setRealClient(null, { dropPending: true })`
140
+ * on reset/teardown to ensure pre-bind Promises don’t hang indefinitely.
141
+ *
142
+ * @param client - The concrete analytics client to bind, or `null` to unbind.
143
+ * @param opts - Options for unbinding behavior.
144
+ * @param opts.dropPending - When unbinding, reject and clear any queued pre-bind async calls.
145
+ */
90
146
  export function setRealClient(client, opts) {
147
+ var _a;
91
148
  realClient = client;
92
149
  if (client) {
93
- const fns = pendingCalls.splice(0, pendingCalls.length);
94
- for (const fn of fns) {
150
+ const items = pendingCalls.splice(0, pendingCalls.length);
151
+ for (const { fn } of items) {
95
152
  try {
96
- const r = fn();
97
- if (r instanceof Promise)
98
- r.catch(() => { });
153
+ Promise.resolve(fn()).catch(() => { });
154
+ }
155
+ catch (err) {
156
+ console.warn("[MetaRouter] replay error:", err);
99
157
  }
100
- catch { }
101
158
  }
102
159
  }
103
160
  else {
104
- if (opts === null || opts === void 0 ? void 0 : opts.dropPending)
161
+ if (opts === null || opts === void 0 ? void 0 : opts.dropPending) {
162
+ for (const it of pendingCalls)
163
+ (_a = it.reject) === null || _a === void 0 ? void 0 : _a.call(it, new Error("[MetaRouter] Proxy dropped before bind"));
105
164
  pendingCalls.length = 0;
165
+ }
106
166
  flushInFlight = null; // reset coalescer
107
167
  }
108
168
  }
@@ -13,7 +13,6 @@ export interface EventWithIdentity extends EventPayload {
13
13
  }
14
14
  export interface EnrichedEventPayload extends EventWithIdentity {
15
15
  messageId: string;
16
- sentAt: string;
17
16
  context: EventContext;
18
17
  writeKey: string;
19
18
  }
@@ -22,6 +21,8 @@ export interface InitOptions {
22
21
  ingestionHost: string;
23
22
  flushIntervalSeconds?: number;
24
23
  debug?: boolean;
24
+ /** Max events held in memory; oldest are dropped once cap is hit (default: 2000) */
25
+ maxQueueEvents?: number;
25
26
  }
26
27
  export interface AnalyticsInterface {
27
28
  track: (event: string, props?: Record<string, any>) => void;
@@ -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,MAA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AAG,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
+ {"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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face CircuitBreakerOptions {
3
+ /** Failures in a row to trip OPEN */
4
+ failureThreshold: number;
5
+ /** Base cooldown when OPEN, ms */
6
+ cooldownMs: number;
7
+ /** Cap for exponential cooldown, ms (optional) */
8
+ maxCooldownMs?: number;
9
+ /** +- jitter ratio (0.0–0.5 recommended), e.g. 0.2 => ±20% */
10
+ jitterRatio?: number;
11
+ /** Allow at most N concurrent HALF_OPEN probes (keep at 1 for simplicity/safety) */
12
+ halfOpenMaxConcurrent?: number;
13
+ /** Optional clock (for tests) */
14
+ now?: () => number;
15
+ /** Optional state transition hookP for logging/metrics */
16
+ onStateChange?: (prev: CircuitState, next: CircuitState, meta: {
17
+ failures: number;
18
+ openCount: number;
19
+ cooldownMs?: number;
20
+ }) => void;
21
+ }
22
+ export default class CircuitBreaker {
23
+ private readonly failureThreshold;
24
+ private readonly baseCooldownMs;
25
+ private readonly maxCooldownMs;
26
+ private readonly jitterRatio;
27
+ private readonly halfOpenMaxConcurrent;
28
+ private readonly now;
29
+ private readonly onStateChange?;
30
+ private consecutiveFailures;
31
+ private state;
32
+ private openUntil;
33
+ private halfOpenInFlight;
34
+ /** how many times we've opened (drives exponential backoff) */
35
+ private openCount;
36
+ constructor(opts: CircuitBreakerOptions);
37
+ /** Should we attempt a request right now? */
38
+ allowRequest(): boolean;
39
+ /** Call on successful request */
40
+ onSuccess(): void;
41
+ /** Call on failed request (retryable only: network/timeout/5xx/etc.) */
42
+ onFailure(): void;
43
+ /** Optional: call for non‑retryable failures (4xx other than 429/413 policy) */
44
+ onNonRetryable(): void;
45
+ /** Time when requests are next allowed (ms since epoch) */
46
+ nextAllowedAt(): number;
47
+ /** How long until next attempt (ms) */
48
+ remainingCooldownMs(): number;
49
+ /** Current state (normalized view: OPEN auto-shows HALF_OPEN after cooldown) */
50
+ getState(): CircuitState;
51
+ private setState;
52
+ private tripOpen;
53
+ }
54
+ //# sourceMappingURL=circuitBreaker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"circuitBrea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AAI,EAAE,qBAAqB;IAavC,6CAA6C;IAC7C,YAAY,IAAI,OAAO;IAyBvB,iCAAiC;IACjC,SAAS,IAAI,IAAI;IAWjB,wEAAwE;IACxE,SAAS,IAAI,IAAI;IAiBjB,gFAAgF;IAChF,cAAc,IAAI,IAAI;IAKtB,2DAA2D;IAC3D,aAAa,IAAI,MAAM;IAUvB,uCAAuC;IACvC,mBAAmB,IAAI,MAAM;IAK7B,gFAAgF;IAChF,QAAQ,IAAI,YAAY;IAYxB,OAAO,CAAC,QAAQ;IAWhB,OAAO,CAAC,QAAQ;CAwBjB"}
@@ -0,0 +1,121 @@
1
+ export default class CircuitBreaker {
2
+ constructor(opts) {
3
+ var _a, _b, _c, _d;
4
+ this.consecutiveFailures = 0;
5
+ this.state = "CLOSED";
6
+ this.openUntil = 0;
7
+ this.halfOpenInFlight = 0;
8
+ /** how many times we've opened (drives exponential backoff) */
9
+ this.openCount = 0;
10
+ this.failureThreshold = Math.max(1, opts.failureThreshold);
11
+ this.baseCooldownMs = Math.max(0, opts.cooldownMs);
12
+ this.maxCooldownMs = Math.max(this.baseCooldownMs, (_a = opts.maxCooldownMs) !== null && _a !== void 0 ? _a : opts.cooldownMs * 8);
13
+ this.jitterRatio = Math.min(Math.max((_b = opts.jitterRatio) !== null && _b !== void 0 ? _b : 0.2, 0), 0.5);
14
+ this.halfOpenMaxConcurrent = Math.max(1, (_c = opts.halfOpenMaxConcurrent) !== null && _c !== void 0 ? _c : 1);
15
+ this.now = (_d = opts.now) !== null && _d !== void 0 ? _d : Date.now;
16
+ this.onStateChange = opts.onStateChange;
17
+ }
18
+ /** Should we attempt a request right now? */
19
+ allowRequest() {
20
+ const t = this.now();
21
+ // Normalize OPEN→HALF_OPEN when cooldown elapsed
22
+ if (this.state === "OPEN" && t >= this.openUntil) {
23
+ this.halfOpenInFlight = 0;
24
+ this.setState("HALF_OPEN");
25
+ }
26
+ if (this.state === "OPEN") {
27
+ // Still cooling down
28
+ return false;
29
+ }
30
+ if (this.state === "HALF_OPEN") {
31
+ if (this.halfOpenInFlight >= this.halfOpenMaxConcurrent)
32
+ return false;
33
+ // Admit a probe
34
+ this.halfOpenInFlight += 1;
35
+ return true;
36
+ }
37
+ // CLOSED
38
+ return true;
39
+ }
40
+ /** Call on successful request */
41
+ onSuccess() {
42
+ if (this.state === "HALF_OPEN") {
43
+ // One successful probe closes the circuit
44
+ this.halfOpenInFlight = 0;
45
+ this.openCount = 0;
46
+ this.setState("CLOSED");
47
+ }
48
+ // Success in CLOSED resets the consecutive failure counter
49
+ this.consecutiveFailures = 0;
50
+ }
51
+ /** Call on failed request (retryable only: network/timeout/5xx/etc.) */
52
+ onFailure() {
53
+ this.consecutiveFailures += 1;
54
+ if (this.state === "HALF_OPEN") {
55
+ // failed probe → re-open with backoff
56
+ this.tripOpen();
57
+ return;
58
+ }
59
+ if (this.state === "CLOSED" &&
60
+ this.consecutiveFailures >= this.failureThreshold) {
61
+ this.tripOpen();
62
+ }
63
+ }
64
+ /** Optional: call for non‑retryable failures (4xx other than 429/413 policy) */
65
+ onNonRetryable() {
66
+ // Do not affect the breaker but clear the run of failures
67
+ this.consecutiveFailures = 0;
68
+ }
69
+ /** Time when requests are next allowed (ms since epoch) */
70
+ nextAllowedAt() {
71
+ const t = this.now();
72
+ if (this.state === "OPEN")
73
+ return this.openUntil;
74
+ if (this.state === "HALF_OPEN") {
75
+ // Capacity-limited in HALF_OPEN; return now (admission depends on allowRequest())
76
+ return t;
77
+ }
78
+ return t; // CLOSED
79
+ }
80
+ /** How long until next attempt (ms) */
81
+ remainingCooldownMs() {
82
+ const t = this.now();
83
+ return Math.max(0, this.nextAllowedAt() - t);
84
+ }
85
+ /** Current state (normalized view: OPEN auto-shows HALF_OPEN after cooldown) */
86
+ getState() {
87
+ // Report HALF_OPEN if cooldown has elapsed,
88
+ // but do not mutate state here — halfOpenInFlight
89
+ // is reset when allowRequest() actually admits a probe.
90
+ if (this.state === "OPEN" && this.now() >= this.openUntil) {
91
+ return "HALF_OPEN";
92
+ }
93
+ return this.state;
94
+ }
95
+ // ---- internals ----
96
+ setState(next, meta = {}) {
97
+ var _a;
98
+ const prev = this.state;
99
+ if (prev === next)
100
+ return;
101
+ this.state = next;
102
+ (_a = this.onStateChange) === null || _a === void 0 ? void 0 : _a.call(this, prev, next, {
103
+ failures: this.consecutiveFailures,
104
+ openCount: this.openCount,
105
+ cooldownMs: meta.cooldownMs,
106
+ });
107
+ }
108
+ tripOpen() {
109
+ // Reset HALF_OPEN counters, move to OPEN, compute cooldown with jitter
110
+ this.halfOpenInFlight = 0;
111
+ // Cap exponent growth (cosmetic; avoids huge exponents)
112
+ const maxExponent = Math.max(0, Math.ceil(Math.log2(this.maxCooldownMs / Math.max(1, this.baseCooldownMs))));
113
+ this.openCount = Math.min(this.openCount + 1, maxExponent + 1);
114
+ const backoff = Math.min(this.maxCooldownMs, this.baseCooldownMs * 2 ** Math.max(0, this.openCount - 1));
115
+ const jitter = backoff * this.jitterRatio;
116
+ const jittered = backoff + (Math.random() * 2 - 1) * jitter;
117
+ const cooldown = Math.max(0, Math.floor(jittered));
118
+ this.openUntil = this.now() + cooldown;
119
+ this.setState("OPEN", { cooldownMs: cooldown });
120
+ }
121
+ }
@@ -6,7 +6,7 @@ import { EnrichedEventPayload, EventContext, EventWithIdentity } from "../types"
6
6
  * - Injects the provided writeKey and context information into the event.
7
7
  * - Returns a new EnrichedEventPayload object, suitable for sending to the ingestion endpoint.
8
8
  *
9
- * @param event The base event with identity information.
9
+ * @param event The base event with identity information.
10
10
  * @param writeKey The write key for the analytics project.
11
11
  * @param context The context information (device, app, environment, etc.).
12
12
  * @returns The enriched event payload.
@@ -1 +1 @@
1
- {"version":3,"file":"enrichEvent.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/enrichEvent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAI,oBAAoB,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAEnF;;;;;;;;;;;GAWG;AACH,wBAAgB,WAAW,CACzB,KAAK,EAAE,iBAAiB,EACxB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,YAAY,GACpB,oBAAoB,CAUtB"}
1
+ {"version":3,"file":"enrichEvent.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/enrichEvent.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,YAAY,EACZ,iBAAiB,EAClB,MAAM,UAAU,CAAC;AAYlB;;;;;;;;;;;GAWG;AACH,wBAAgB,WAAW,CACzB,KAAK,EAAE,iBAAiB,EACxB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,YAAY,GACpB,oBAAoB,CAStB"}
@@ -1,3 +1,12 @@
1
+ import uuid from "react-native-uuid";
2
+ /**
3
+ * Generate a messageId with a timestamp prefix (ms since epoch + UUID).
4
+ * This makes it easy to debug when events were created.
5
+ */
6
+ function generateMessageId() {
7
+ const ts = Date.now(); // ms since epoch
8
+ return `${ts}-${uuid.v4()}`;
9
+ }
1
10
  /**
2
11
  * Enriches an analytics event with additional metadata required for ingestion.
3
12
  *
@@ -5,7 +14,7 @@
5
14
  * - Injects the provided writeKey and context information into the event.
6
15
  * - Returns a new EnrichedEventPayload object, suitable for sending to the ingestion endpoint.
7
16
  *
8
- * @param event The base event with identity information.
17
+ * @param event The base event with identity information.
9
18
  * @param writeKey The write key for the analytics project.
10
19
  * @param context The context information (device, app, environment, etc.).
11
20
  * @returns The enriched event payload.
@@ -14,8 +23,7 @@ export function enrichEvent(event, writeKey, context) {
14
23
  const enriched = {
15
24
  ...event,
16
25
  writeKey,
17
- messageId: `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`,
18
- sentAt: new Date().toISOString(),
26
+ messageId: generateMessageId(),
19
27
  context,
20
28
  };
21
29
  return enriched;
package/lib/index.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- import "react-native-get-random-values";
2
1
  export { createAnalyticsClient } from "./analytics/init";
3
2
  export { MetaRouterProvider } from "./react/context";
4
3
  export { useMetaRouter } from "./react/useMetaRouter";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,gCAAgC,CAAC;AAExC,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAEzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,YAAY,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAEzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,YAAY,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC"}
package/lib/index.js CHANGED
@@ -1,4 +1,3 @@
1
- import "react-native-get-random-values";
2
1
  export { createAnalyticsClient } from "./analytics/init";
3
2
  export { MetaRouterProvider } from "./react/context";
4
3
  export { useMetaRouter } from "./react/useMetaRouter";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metarouter/react-native-sdk",
3
- "version": "1.1.7",
3
+ "version": "1.2.0",
4
4
  "main": "./lib/index.js",
5
5
  "types": "./lib/index.d.ts",
6
6
  "exports": {
@@ -36,13 +36,12 @@
36
36
  "url": "https://github.com/metarouterio/react-native-sdk"
37
37
  },
38
38
  "dependencies": {
39
- "react-native-get-random-values": "^1.11.0",
40
- "uuid": "^11.1.0"
39
+ "react-native-uuid": "^2.0.3"
41
40
  },
42
41
  "peerDependencies": {
43
- "react-native": ">=0.63.0",
44
- "react": ">=16.8.0",
45
42
  "@react-native-async-storage/async-storage": ">=2.2.0",
43
+ "react": ">=16.8.0",
44
+ "react-native": ">=0.63.0",
46
45
  "react-native-device-info": "^14.0.4"
47
46
  },
48
47
  "devDependencies": {
@@ -1,8 +0,0 @@
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>;
8
- //# sourceMappingURL=retry.d.ts.map
@@ -1 +0,0 @@
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,23 +0,0 @@
1
- export async function retryWithBackoff(fn, opts = {}) {
2
- const { retries = 5, baseDelayMs = 1000, sleep = (ms) => new Promise((res) => setTimeout(res, ms)), shouldContinue = () => true, } = opts;
3
- let attempt = 0;
4
- while (attempt < retries) {
5
- if (!shouldContinue())
6
- throw new Error("Retry aborted by shouldContinue");
7
- try {
8
- return await fn();
9
- }
10
- catch (err) {
11
- attempt++;
12
- if (attempt === retries)
13
- throw err;
14
- const jitter = Math.random() * 100;
15
- const delay = baseDelayMs * 2 ** (attempt - 1) + jitter;
16
- await sleep(delay);
17
- if (!shouldContinue())
18
- throw new Error("Retry aborted by shouldContinue");
19
- }
20
- }
21
- // Unreachable, but TS likes a return/throw
22
- throw new Error("Exhausted all retries");
23
- }