Skip to content

Instantly share code, notes, and snippets.

@JohnMurray
Last active June 21, 2018 21:45
Show Gist options
  • Save JohnMurray/35fab48d008594dcf6dd6dbe1d013a90 to your computer and use it in GitHub Desktop.
Save JohnMurray/35fab48d008594dcf6dd6dbe1d013a90 to your computer and use it in GitHub Desktop.
Adding user-defined rate-limit-error checking
class ApiService[T](limit: Long, timeFrame: FiniteDuration) {
// other code ...
type LimitDetector = PartialFunction[Either[Throwable, T], Boolean]
case class RequestQueueItem(f: () => Future[T],
p: Promise[T],
limitDetector: LimitDetector)
private var limitDetection: LimitDetector = {
case Left(_) => true
case Right(_) => false
}
def withDefaultLimitDetection(d: LimitDetector): ApiService[t] = {
limitDetection = d
this
}
def request(f: () => Future[T])
(d: LimitDetector = limitDetection)
: Future[T] = this.synchronized {
val p = Promise[T]()
requestQueue.offerLast(RequestQueueItem(f, p, d))
tryRequest()
p.future
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment