'use strict' const DEFAULT_BUDGET_PER_SEC = Math.max( 5, Number(process.env.PEARCORD_POLL_DB_READ_BUDGET_PER_SEC) || 120 ) const WINDOW_MS = 1000 function createPollDbReadBudget (budgetPerSec = DEFAULT_BUDGET_PER_SEC) { let windowStart = Date.now() let count = 0 let warned = 0 let lastWarnAt = 0 return { record (n = 1, { log } = {}) { const now = Date.now() if (now - windowStart >= WINDOW_MS) { windowStart = now count = 0 } count += Math.max(0, Number(n) || 0) if (count > budgetPerSec && now - lastWarnAt > WINDOW_MS) { warned += 1 lastWarnAt = now log?.warn?.('poll-path db read budget exceeded', { count, budgetPerSec, windowMs: WINDOW_MS }) } return { count, budgetPerSec, exceeded: count > budgetPerSec } }, stats () { return { count, budgetPerSec, warned, windowStart } } } } module.exports = { createPollDbReadBudget, DEFAULT_BUDGET_PER_SEC }