Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 10 additions & 19 deletions packages/cli-kit/src/private/node/conf-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,26 +241,17 @@ export async function runWithRateLimit(options: RunWithRateLimitOptions, config
const cached = cache[cacheKey]
const now = Date.now()

if (cached?.value) {
// First sweep through the cache and eliminate old events
const windowStart = now - timeIntervalToMilliseconds(timeout)
const occurrences = cached.value.filter((occurrence) => occurrence >= windowStart)

// Now check that the number of occurrences within the interval is below the limit
if (occurrences.length >= limit) {
// First remove the old occurrences from the cache
cache[cacheKey] = {value: occurrences, timestamp: Date.now()}
config.set('cache', cache)

return false
}

await task()
cache[cacheKey] = {value: [...occurrences, now], timestamp: now}
} else {
await task()
cache[cacheKey] = {value: [now], timestamp: now}
const windowStart = now - timeIntervalToMilliseconds(timeout)
const occurrences = cached?.value ? cached.value.filter((occurrence) => occurrence >= windowStart) : []

if (occurrences.length >= limit) {
cache[cacheKey] = {value: occurrences, timestamp: now}
config.set('cache', cache)
return false
}

await task()
cache[cacheKey] = {value: [...occurrences, now], timestamp: now}
config.set('cache', cache)

return true
Expand Down
Loading