Repository navigation
fix(analytics): avoid sending the same JavaScript-mode batch twice #484
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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,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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
If a request takes longer than two minutes, a later timer flush replaces its lock and sends the same queued batch again. The Knowledge Base Used: Event delivery and persistence Prompt To Fix With AIThis 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, | ||
|
|
@@ -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}` | ||
| ); | ||
| } | ||
| }; | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Both queue mocks ignore the endpoint, and each request overwrites
finishRequest. The firstflush()starts all three endpoints, sofinishRequest()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 forMixpanelType.EVENTS, resolve that request, and check that a later flush can send another event.Prompt To Fix With AI