Improve token management logic

This commit is contained in:
Zed 2021-12-20 04:19:11 +01:00
parent 7af71ec480
commit 5b185c79de
2 changed files with 3 additions and 7 deletions

View File

@ -53,10 +53,8 @@ proc fetch*(url: Uri; oldApi=false): Future[JsonNode] {.async.} =
result = newJNull() result = newJNull()
if not oldApi and resp.headers.hasKey(rl & "reset"): if not oldApi and resp.headers.hasKey(rl & "reset"):
let time = fromUnix(parseInt(resp.headers[rl & "reset"])) token.remaining = parseInt(resp.headers[rl & "remaining"])
if token.reset != time: token.reset = fromUnix(parseInt(resp.headers[rl & "reset"]))
token.remaining = parseInt(resp.headers[rl & "limit"])
token.reset = time
if result.getError notin {invalidToken, forbidden, badToken}: if result.getError notin {invalidToken, forbidden, badToken}:
token.lastUse = getTime() token.lastUse = getTime()

View File

@ -57,7 +57,7 @@ template expired(token: Token): untyped =
token.lastUse < time - maxLastUse token.lastUse < time - maxLastUse
template isLimited(token: Token): untyped = template isLimited(token: Token): untyped =
token == nil or (token.remaining <= 1 and token.reset > getTime()) or token == nil or (token.remaining <= 5 and token.reset > getTime()) or
token.expired token.expired
proc release*(token: Token; invalid=false) = proc release*(token: Token; invalid=false) =
@ -79,8 +79,6 @@ proc getToken*(): Future[Token] {.async.} =
if result == nil: if result == nil:
raise rateLimitError() raise rateLimitError()
dec result.remaining
proc poolTokens*(amount: int) {.async.} = proc poolTokens*(amount: int) {.async.} =
var futs: seq[Future[Token]] var futs: seq[Future[Token]]
for i in 0 ..< amount: for i in 0 ..< amount: