chore: global sync per minute safety limit (#2765)

This commit is contained in:
Karol Sójko
2024-01-11 15:26:09 +01:00
committed by GitHub
parent 3d895ca499
commit cf4b5ccf0a
11 changed files with 140 additions and 10 deletions

View File

@@ -0,0 +1,40 @@
import { SyncFrequencyGuardInterface } from './SyncFrequencyGuardInterface'
export class SyncFrequencyGuard implements SyncFrequencyGuardInterface {
private callsPerMinuteMap: Map<string, number>
constructor(private syncCallsThresholdPerMinute: number) {
this.callsPerMinuteMap = new Map<string, number>()
}
isSyncCallsThresholdReachedThisMinute(): boolean {
const stringDateToTheMinute = this.getCallsPerMinuteKey()
const persistedCallsCount = this.callsPerMinuteMap.get(stringDateToTheMinute) || 0
return persistedCallsCount >= this.syncCallsThresholdPerMinute
}
incrementCallsPerMinute(): void {
const stringDateToTheMinute = this.getCallsPerMinuteKey()
const persistedCallsCount = this.callsPerMinuteMap.get(stringDateToTheMinute)
const newMinuteStarted = persistedCallsCount === undefined
if (newMinuteStarted) {
this.clear()
this.callsPerMinuteMap.set(stringDateToTheMinute, 1)
} else {
this.callsPerMinuteMap.set(stringDateToTheMinute, persistedCallsCount + 1)
}
}
clear(): void {
this.callsPerMinuteMap.clear()
}
private getCallsPerMinuteKey(): string {
const now = new Date()
return `${now.getFullYear()}-${now.getMonth()}-${now.getDate()}T${now.getHours()}:${now.getMinutes()}`
}
}