Skip to content

Instantly share code, notes, and snippets.

@oliviertassinari
Last active January 23, 2017 09:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oliviertassinari/114792721df8b7ef2cf2ecf3e4dea621 to your computer and use it in GitHub Desktop.
Save oliviertassinari/114792721df8b7ef2cf2ecf3e4dea621 to your computer and use it in GitHub Desktop.
Prevent duplicate issues from same user https://github.com/getsentry/raven-js/issues/530
// @flow weak
function now() {
return +new Date(); // timestamp in ms
}
// Count the number of events sent over the last period of time.
const count = {
minute: {
slot: 0,
budgetUsed: 0,
},
hour: {
slot: 0,
budgetUsed: 0,
},
};
function filterThrottle(options) {
const {
maxBudgetMinute,
maxBudgetHour,
getDate = now,
} = options;
return () => {
const timestamp = getDate();
const minuteSlot = Math.round(timestamp / 1000 / 60);
const hourSlot = Math.round(timestamp / 1000 / 60 / 60);
// We are on a new minute slot.
if (count.minute.slot !== minuteSlot) {
count.minute.slot = minuteSlot;
count.minute.budgetUsed = 0;
}
// We are on a new hour slot.
if (count.hour.slot !== hourSlot) {
count.hour.slot = hourSlot;
count.hour.budgetUsed = 0;
}
// Check minute usage
if (count.minute.budgetUsed < maxBudgetMinute) {
count.minute.budgetUsed++;
// Check hour usage
if (count.hour.budgetUsed < maxBudgetHour) {
count.hour.budgetUsed++;
return true;
}
}
return false;
};
}
export default filterThrottle;
// @flow weak
import {assert} from 'chai';
import filterThrottle from './filterThrottle';
describe.only('crashReporter/filterThrottle', () => {
it('should work', () => {
let hour = 0;
let minute = 0;
const shouldSendCallback = filterThrottle({
maxBudgetMinute: 2,
maxBudgetHour: 5,
getDate: () => (hour * 60 + minute) * 60 * 1000, // timestamp ms
});
assert.strictEqual(shouldSendCallback(), true);
assert.strictEqual(shouldSendCallback(), true);
assert.strictEqual(shouldSendCallback(), false);
minute++;
assert.strictEqual(shouldSendCallback(), true);
assert.strictEqual(shouldSendCallback(), true);
assert.strictEqual(shouldSendCallback(), false);
minute++;
assert.strictEqual(shouldSendCallback(), true);
assert.strictEqual(shouldSendCallback(), false);
minute++;
assert.strictEqual(shouldSendCallback(), false);
minute++;
hour++;
assert.strictEqual(shouldSendCallback(), true);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment