Skip to content

Commit

Permalink
change callback logic
Browse files Browse the repository at this point in the history
  • Loading branch information
0OZ committed Jun 24, 2024
1 parent d76d795 commit d2b8a0d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/main/kotlin/io.evest.simpleratelimiter/RateLimiter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,18 @@ object RateLimiter {
}

/**
* Try to bucket the call, if the rate limit is exceeded, return an [Option] with the exception.
* Bucket the call, if the rate limit is exceeded, call the [error] function.
*/
fun <T> T.tryBucket(
key: String,
maxCalls: Int = 1,
per: Duration = Duration.ofSeconds(defaultMinWait),
): Option<T> = when (BucketHandler.count(key, maxCalls, per)) {
true -> Option(this, RateLimitException("Rate limit exceeded for key: $key"))
false -> Option(this)
error: (exception: RateLimitException?) -> Unit = {},
): T = also {
val exhausted = when (BucketHandler.count(key, maxCalls, per)) {
true -> RateLimitException("Rate limit exceeded for key: $key")
false -> null
}
error(exhausted)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package io.evest.simpleratelimiter.test

import io.evest.simpleratelimiter.RateLimitException
import io.evest.simpleratelimiter.RateLimiter.bucket
import io.evest.simpleratelimiter.RateLimiter.tryBucket
import java.time.Duration
import kotlin.test.Test

Expand All @@ -15,6 +16,7 @@ class TestRateLimiter {
val startTime = System.currentTimeMillis()
try {
any.bucket("1", 2, Duration.ofSeconds(1))

} catch (e: RateLimitException) {
println("Rate limit exceeded for iteration $i")
}
Expand Down

0 comments on commit d2b8a0d

Please sign in to comment.