File tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed
src/commonMain/kotlin/spp.protocol/instrument Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ package spp.protocol.instrument
2+
3+ import kotlinx.datetime.Clock
4+ import kotlin.jvm.Transient
5+
6+ class HitThrottle (private val limit : Int , step : HitThrottleStep ) {
7+
8+ private val step: HitThrottleStep
9+
10+ @Transient
11+ private var lastReset: Long = - 1
12+
13+ @Transient
14+ private var hitCount = 0
15+
16+ @Transient
17+ var totalHitCount = 0
18+ private set
19+
20+ @Transient
21+ var totalLimitedCount = 0
22+ private set
23+
24+ init {
25+ this .step = step
26+ }
27+
28+ fun isRateLimited (): Boolean {
29+ if (hitCount++ < limit) {
30+ totalHitCount++
31+ return false
32+ }
33+ return if (Clock .System .now().toEpochMilliseconds() - lastReset > step.toMillis(1 )) {
34+ hitCount = 1
35+ totalHitCount++
36+ lastReset = Clock .System .now().toEpochMilliseconds()
37+ false
38+ } else {
39+ totalLimitedCount++
40+ true
41+ }
42+ }
43+ }
Original file line number Diff line number Diff line change 1+ package spp.protocol.instrument
2+
3+ enum class HitThrottleStep (private val millis : Int ) {
4+ SECOND (1000 ),
5+ MINUTE (1000 * 60 ),
6+ HOUR (1000 * 60 * 60 ),
7+ DAY (1000 * 60 * 60 * 24 );
8+
9+ fun toMillis (duration : Long ): Long {
10+ return millis * duration
11+ }
12+ }
You can’t perform that action at this time.
0 commit comments