nitter/src/tokens.nim

132 lines
3.6 KiB
Nim
Raw Normal View History

2021-12-27 01:37:38 +00:00
# SPDX-License-Identifier: AGPL-3.0-only
import asyncdispatch, times, json, random, strutils, tables
import types
2020-06-01 00:16:24 +00:00
# max requests at a time per account to avoid race conditions
const
maxConcurrentReqs = 5
dayInSeconds = 24 * 60 * 60
2020-07-09 07:18:14 +00:00
var
accountPool: seq[GuestAccount]
2022-06-05 19:47:25 +00:00
enableLogging = false
template log(str) =
if enableLogging: echo "[accounts] ", str
2022-01-05 23:42:18 +00:00
proc getPoolJson*(): JsonNode =
var
list = newJObject()
totalReqs = 0
totalPending = 0
reqsPerApi: Table[string, int]
let now = epochTime().int
for account in accountPool:
totalPending.inc(account.pending)
list[account.id] = %*{
"apis": newJObject(),
"pending": account.pending,
}
for api in account.apis.keys:
let obj = %*{}
if account.apis[api].limited:
obj["limited"] = %true
if account.apis[api].reset > now.int:
obj["remaining"] = %account.apis[api].remaining
list[account.id]["apis"][$api] = obj
if "remaining" notin obj:
continue
2022-01-05 23:42:18 +00:00
let
maxReqs =
case api
of Api.search: 50
2023-07-22 02:06:04 +00:00
of Api.photoRail: 180
of Api.userTweets, Api.userTweetsAndReplies, Api.userMedia,
Api.userRestId, Api.userScreenName,
Api.tweetDetail, Api.tweetResult,
Api.list, Api.listTweets, Api.listMembers, Api.listBySlug: 500
reqs = maxReqs - account.apis[api].remaining
2022-01-05 23:42:18 +00:00
reqsPerApi[$api] = reqsPerApi.getOrDefault($api, 0) + reqs
totalReqs.inc(reqs)
return %*{
"amount": accountPool.len,
2022-01-05 23:42:18 +00:00
"requests": totalReqs,
"pending": totalPending,
"apis": reqsPerApi,
"accounts": list
2022-01-05 23:42:18 +00:00
}
proc rateLimitError*(): ref RateLimitError =
2022-01-05 21:48:45 +00:00
newException(RateLimitError, "rate limited")
2020-06-01 00:16:24 +00:00
proc isLimited(account: GuestAccount; api: Api): bool =
if account.isNil:
2022-01-05 21:48:45 +00:00
return true
if api in account.apis:
let limit = account.apis[api]
if limit.limited and (epochTime().int - limit.limitedAt) > dayInSeconds:
account.apis[api].limited = false
2023-08-21 12:49:50 +00:00
log "resetting limit, api: ", api, ", id: ", account.id
return limit.limited or (limit.remaining <= 10 and limit.reset > epochTime().int)
2022-01-05 21:48:45 +00:00
else:
return false
2020-06-01 00:16:24 +00:00
proc isReady(account: GuestAccount; api: Api): bool =
not (account.isNil or account.pending > maxConcurrentReqs or account.isLimited(api))
proc release*(account: GuestAccount; used=false; invalid=false) =
if account.isNil: return
if invalid:
log "discarding invalid account: " & account.id
2022-06-05 19:47:25 +00:00
let idx = accountPool.find(account)
if idx > -1: accountPool.delete(idx)
elif used:
dec account.pending
2020-06-01 00:16:24 +00:00
proc getGuestAccount*(api: Api): Future[GuestAccount] {.async.} =
for i in 0 ..< accountPool.len:
if result.isReady(api): break
release(result)
result = accountPool.sample()
if not result.isNil and result.isReady(api):
inc result.pending
else:
log "no accounts available for API: " & $api
raise rateLimitError()
proc setRateLimit*(account: GuestAccount; api: Api; remaining, reset: int) =
# avoid undefined behavior in race conditions
if api in account.apis:
let limit = account.apis[api]
if limit.reset >= reset and limit.remaining < remaining:
return
if limit.reset == reset and limit.remaining >= remaining:
account.apis[api].remaining = remaining
return
account.apis[api] = RateLimit(remaining: remaining, reset: reset)
2020-06-01 00:16:24 +00:00
proc initAccountPool*(cfg: Config; accounts: JsonNode) =
2022-06-05 19:47:25 +00:00
enableLogging = cfg.enableDebug
for account in accounts:
accountPool.add GuestAccount(
id: account{"user", "id_str"}.getStr,
oauthToken: account{"oauth_token"}.getStr,
oauthSecret: account{"oauth_token_secret"}.getStr,
)