segmentio / analytics-node

The hassle-free way to integrate analytics into any node application.

Home Page:https://segment.com/libraries/node

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`enque` callback called twice when flush is triggered

yo1dog opened this issue · comments

commented

The callback passed to enque can be called twice if a flush is triggered. The callback is passed both to the queued message and to flush:

analytics-node/index.js

Lines 210 to 223 in 70f24fe

this.queue.push({ message, callback })
if (!this.flushed) {
this.flushed = true
this.flush(callback)
return
}
const hasReachedFlushAt = this.queue.length >= this.flushAt
const hasReachedQueueSize = this.queue.reduce((acc, item) => acc + JSON.stringify(item).length, 0) >= this.maxQueueSize
if (hasReachedFlushAt || hasReachedQueueSize) {
this.flush(callback)
return
}

When flush's done function is called, the callback is called twice: Once from the callbacks array (as it was added to the array from the queued message) and again when callback is called (as it was passed to flush as the callback argument).

analytics-node/index.js

Lines 265 to 268 in 70f24fe

const done = err => {
callbacks.forEach(callback => callback(err))
callback(err, data)
}

The fix is to not pass enque's callback to flush.

In general, a callback should never have more than 1 handler.

Hello @yo1dog, this issue will be solved with pr #299 which I requested to merge ASAP.
Thanks for your contribution again!

Segment team