diff --git a/__tests__/core.test.js b/__tests__/core.test.js index ac397fb0..9d1a6097 100644 --- a/__tests__/core.test.js +++ b/__tests__/core.test.js @@ -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(), }, })); @@ -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)) + ); + + // 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); + }); + }); }); diff --git a/javascript/mixpanel-core.js b/javascript/mixpanel-core.js index d866aa96..0ad34152 100644 --- a/javascript/mixpanel-core.js +++ b/javascript/mixpanel-core.js @@ -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(); @@ -101,10 +108,36 @@ 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); + 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, @@ -112,6 +145,7 @@ export const MixpanelCore = (storage) => { ); const batchSize = config.getFlushBatchSize(token); const batch = queue.slice(0, batchSize); + let removeCount = batch.length; try { await MixpanelNetwork.sendRequest({ token, @@ -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}` - ); } };