Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 81 additions & 0 deletions __tests__/core.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ jest.mock("mixpanel-react-native/javascript/mixpanel-config", () => ({
jest.mock("mixpanel-react-native/javascript/mixpanel-logger", () => ({
MixpanelLogger: {
log: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
},
}));
Expand Down Expand Up @@ -132,4 +133,84 @@ describe("MixpanelQueueManager", () => {
await MixpanelCore().flush(token);
expect(MixpanelNetwork.sendRequest).toHaveBeenCalledTimes(0);
});

it("does not send the same batch twice while a request is in flight", async () => {
const queue = [data];
MixpanelQueueManager.getQueue.mockImplementation(() => [...queue]);
MixpanelQueueManager.spliceQueue.mockImplementation(async (t, ty, start, count) => {
queue.splice(start, count);
});
let finishRequest;
MixpanelNetwork.sendRequest.mockImplementation(
() => new Promise((resolve) => (finishRequest = resolve))
);
Comment on lines +139 to +146

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Test completes the wrong request

Both queue mocks ignore the endpoint, and each request overwrites finishRequest. The first flush() starts all three endpoints, so finishRequest() completes /groups/ and empties their shared fake queue. The test passes with /track/ still pending, so it cannot catch a missing lock release after event delivery. Return data only for MixpanelType.EVENTS, resolve that request, and check that a later flush can send another event.

Prompt To Fix With AI
This is a comment left during a code review.
Path: __tests__/core.test.js
Line: 138-145

Comment:
**Test completes the wrong request**

Both queue mocks ignore the endpoint, and each request overwrites `finishRequest`. The first `flush()` starts all three endpoints, so `finishRequest()` completes `/groups/` and empties their shared fake queue. The test passes with `/track/` still pending, so it cannot catch a missing lock release after event delivery. Return data only for `MixpanelType.EVENTS`, resolve that request, and check that a later flush can send another event.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.


// Two instances for the same token (e.g. a component that creates its own
// Mixpanel) flush the shared queue at the same time.
await MixpanelCore().flush("in-flight-token");
await MixpanelCore().flush("in-flight-token");
finishRequest();
await new Promise(setImmediate);

const trackCalls = MixpanelNetwork.sendRequest.mock.calls.filter(
([args]) => args.endpoint === MixpanelType.EVENTS
);
expect(trackCalls).toHaveLength(1);
expect(queue).toHaveLength(0);
});

describe("with an events-only queue", () => {
let queue;
// Scope the queue to one token so flush loops left running by other tests
// (e.g. "flushes the queue") can't send or remove these events.
let queueToken;
const eventSends = () =>
MixpanelNetwork.sendRequest.mock.calls.filter(
([args]) => args.token === queueToken && args.endpoint === MixpanelType.EVENTS
).length;

beforeEach(() => {
queue = [data];
MixpanelQueueManager.getQueue.mockImplementation((t, ty) =>
t === queueToken && ty === MixpanelType.EVENTS ? [...queue] : []
);
MixpanelQueueManager.spliceQueue.mockImplementation(async (t, ty, start, count) => {
queue.splice(start, count);
});
MixpanelNetwork.sendRequest.mockResolvedValue(undefined);
});

it("starts a new flush when the in-flight request never settles", async () => {
queueToken = "stuck-token";
MixpanelNetwork.sendRequest.mockImplementationOnce(() => new Promise(() => {}));
const now = jest.spyOn(Date, "now").mockReturnValue(1000);

await MixpanelCore().flush("stuck-token");
now.mockReturnValue(1000 + 60 * 1000); // still within the retry window
await MixpanelCore().flush("stuck-token");
expect(eventSends()).toBe(1);

now.mockReturnValue(1000 + 3 * 60 * 1000);
await MixpanelCore().flush("stuck-token");
await new Promise(setImmediate);
expect(eventSends()).toBe(2);
expect(queue).toHaveLength(0);
now.mockRestore();
});

it("releases the flush when processing throws unexpectedly", async () => {
queueToken = "throwing-token";
MixpanelQueueManager.getQueue.mockImplementationOnce(() => {
throw new Error("storage failure");
});

await MixpanelCore().flush("throwing-token");
await new Promise(setImmediate);
await MixpanelCore().flush("throwing-token");
await new Promise(setImmediate);

expect(eventSends()).toBe(1);
expect(queue).toHaveLength(0);
});
});
});
92 changes: 62 additions & 30 deletions javascript/mixpanel-core.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ import { MixpanelConfig } from "./mixpanel-config";
import { MixpanelPersistent } from "./mixpanel-persistent";
import { MixpanelLogger } from "./mixpanel-logger";

// One flush per token and endpoint at a time; the queue is shared by every
// instance for a token. A flush whose current batch has been pending longer
// than sendRequest's full retry window (~62s of backoff) is treated as stuck,
// so a request that never settles can't block flushing for the session.
const FLUSH_LOCK_STALE_MS = 2 * 60 * 1000;
const flushLocks = new Map();

export const MixpanelCore = (storage) => {
const mixpanelPersistent = MixpanelPersistent.getInstance(storage);
const config = MixpanelConfig.getInstance();
Expand Down Expand Up @@ -101,17 +108,44 @@ export const MixpanelCore = (storage) => {
};

const processQueue = async (token, type) => {
const flushKey = `${token}|${type}`;
const current = flushLocks.get(flushKey);
if (current && Date.now() - current.batchStartedAt < FLUSH_LOCK_STALE_MS) {
MixpanelLogger.log(token, `Flush already in progress for endpoint: ${type}`);
return;
}
if (current) {
MixpanelLogger.warn(
token,
`Previous flush for endpoint ${type} appears stuck, starting a new one.`
);
}
const lock = { batchStartedAt: Date.now() };
flushLocks.set(flushKey, lock);
Comment on lines +113 to +124

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Slow requests send batches twice

If a request takes longer than two minutes, a later timer flush replaces its lock and sends the same queued batch again. sendRequest has no timeout or cancellation, and its 62 seconds of backoff excludes time spent in fetch and response.json(). The old request can therefore still deliver or retry the batch, causing duplicate events or profile updates.

The ownsLock() check only stops the old request from removing records. Keep the lock until the request settles, or stop the old request and its retries before replacing it.

Knowledge Base Used: Event delivery and persistence

Prompt To Fix With AI
This is a comment left during a code review.
Path: javascript/mixpanel-core.js
Line: 113-124

Comment:
**Slow requests send batches twice**

If a request takes longer than two minutes, a later timer flush replaces its lock and sends the same queued batch again. `sendRequest` has no timeout or cancellation, and its 62 seconds of backoff excludes time spent in `fetch` and `response.json()`. The old request can therefore still deliver or retry the batch, causing duplicate events or profile updates.

The `ownsLock()` check only stops the old request from removing records. Keep the lock until the request settles, or stop the old request and its retries before replacing it.

**Knowledge Base Used:** [Event delivery and persistence](https://app.greptile.com/-/switch-tenant?tenant=mixpanel&next=%2Fcustom-context%2Fknowledge-base%2Fmixpanel%2Fmixpanel-react-native%2F-%2Fdocs%2Fevent-delivery-and-persistence.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.


MixpanelLogger.log(token, `Processing queue for endpoint: ${type}`);
const processBatch = async () => {
const queue = MixpanelQueueManager.getQueue(token, type);
if (queue.length > 0) {
drainQueue(token, type, flushKey, lock);
};

const drainQueue = async (token, type, flushKey, lock) => {
// A newer flush may take over a stuck lock; this loop then stops without
// touching the queue, so it can't remove events the new flush hasn't sent.
const ownsLock = () => flushLocks.get(flushKey) === lock;
try {
while (ownsLock()) {
const queue = MixpanelQueueManager.getQueue(token, type);
if (queue.length === 0) {
return;
}
lock.batchStartedAt = Date.now();
MixpanelLogger.log(token, `[Flushing queue] endpoint: ${type}`);
MixpanelLogger.log(
token,
`[Flushing queue] queue: ${JSON.stringify(queue)}`
);
const batchSize = config.getFlushBatchSize(token);
const batch = queue.slice(0, batchSize);
let removeCount = batch.length;
try {
await MixpanelNetwork.sendRequest({
token,
Expand All @@ -121,36 +155,34 @@ export const MixpanelCore = (storage) => {
useIPAddressForGeoLocation:
config.getUseIpAddressForGeolocation(token),
});
await MixpanelQueueManager.spliceQueue(token, type, 0, batch.length);
// Process the next batch if there are more events in the queue
const queue = MixpanelQueueManager.getQueue(token, type);
if (queue.length > 0) {
setTimeout(processBatch, 0);
}
} catch (error) {
handleBatchError(token, error, type, processBatch);
if (error.code !== 400) {
MixpanelLogger.error(
token,
`Error sending event batch from queue, error: ${error}`
);
return;
}
MixpanelLogger.error(
token,
`Bad request received due to corrupted data within the batch. The corrupted data is now being removed from the queue...`
);
// Remove the corrupted data from the queue, to avoid the data loss, only remove one event at a time
removeCount = 1;
}
if (!ownsLock()) {
return;
}
await MixpanelQueueManager.spliceQueue(token, type, 0, removeCount);
// Yield before the next batch
await new Promise((resolve) => setTimeout(resolve, 0));
}
} catch (error) {
MixpanelLogger.error(token, `Error flushing queue, error: ${error}`);
} finally {
if (ownsLock()) {
flushLocks.delete(flushKey);
}
};

processBatch();
};

const handleBatchError = (token, error, type, callback) => {
if (error.code === 400) {
MixpanelLogger.error(
token,
`Bad request received due to corrupted data within the batch. The corrupted data is now being removed from the queue...`
);
// Remove the corrupted data from the queue, to avoid the data loss, only remove one event at a time
MixpanelQueueManager.spliceQueue(token, type, 0, 1).then(() => {
setTimeout(callback, 0);
});
} else {
MixpanelLogger.error(
token,
`Error sending event batch from queue, error: ${error}`
);
}
};

Expand Down
Loading