tokens.nim 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. #SPDX-License-Identifier: AGPL-3.0-only
  2. import asyncdispatch, times, json, random, strutils, tables, sets
  3. import types
  4. # max requests at a time per account to avoid race conditions
  5. const
  6. maxConcurrentReqs = 2
  7. dayInSeconds = 24 * 60 * 60
  8. var
  9. accountPool: seq[GuestAccount]
  10. enableLogging = false
  11. template log(str) =
  12. if enableLogging: echo "[accounts] ", str
  13. proc getPoolJson*(): JsonNode =
  14. var
  15. list = newJObject()
  16. totalReqs = 0
  17. totalPending = 0
  18. limited: HashSet[string]
  19. reqsPerApi: Table[string, int]
  20. let now = epochTime().int
  21. for account in accountPool:
  22. totalPending.inc(account.pending)
  23. var includeAccount = false
  24. let accountJson = %*{
  25. "apis": newJObject(),
  26. "pending": account.pending,
  27. }
  28. for api in account.apis.keys:
  29. let
  30. apiStatus = account.apis[api]
  31. obj = %*{}
  32. if apiStatus.reset > now.int:
  33. obj["remaining"] = %apiStatus.remaining
  34. if "remaining" notin obj and not apiStatus.limited:
  35. continue
  36. if apiStatus.limited:
  37. obj["limited"] = %true
  38. limited.incl account.id
  39. accountJson{"apis", $api} = obj
  40. includeAccount = true
  41. let
  42. maxReqs =
  43. case api
  44. of Api.search: 50
  45. of Api.tweetDetail: 150
  46. of Api.photoRail: 180
  47. of Api.userTweets, Api.userTweetsAndReplies, Api.userMedia,
  48. Api.userRestId, Api.userScreenName,
  49. Api.tweetResult,
  50. Api.list, Api.listTweets, Api.listMembers, Api.listBySlug: 500
  51. of Api.userSearch: 900
  52. reqs = maxReqs - apiStatus.remaining
  53. reqsPerApi[$api] = reqsPerApi.getOrDefault($api, 0) + reqs
  54. totalReqs.inc(reqs)
  55. if includeAccount:
  56. list[account.id] = accountJson
  57. return %*{
  58. "amount": accountPool.len,
  59. "limited": limited.card,
  60. "requests": totalReqs,
  61. "pending": totalPending,
  62. "apis": reqsPerApi,
  63. "accounts": list
  64. }
  65. proc rateLimitError*(): ref RateLimitError =
  66. newException(RateLimitError, "rate limited")
  67. proc isLimited(account: GuestAccount; api: Api): bool =
  68. if account.isNil:
  69. return true
  70. if api in account.apis:
  71. let limit = account.apis[api]
  72. if limit.limited and (epochTime().int - limit.limitedAt) > dayInSeconds:
  73. account.apis[api].limited = false
  74. log "resetting limit, api: " & $api & ", id: " & $account.id
  75. return limit.limited or (limit.remaining <= 10 and limit.reset > epochTime().int)
  76. else:
  77. return false
  78. proc isReady(account: GuestAccount; api: Api): bool =
  79. not (account.isNil or account.pending > maxConcurrentReqs or account.isLimited(api))
  80. proc release*(account: GuestAccount; used=false; invalid=false) =
  81. if account.isNil: return
  82. if invalid:
  83. log "discarding invalid account: " & account.id
  84. let idx = accountPool.find(account)
  85. if idx > -1: accountPool.delete(idx)
  86. elif used:
  87. dec account.pending
  88. proc getGuestAccount*(api: Api): Future[GuestAccount] {.async.} =
  89. for i in 0 ..< accountPool.len:
  90. if result.isReady(api): break
  91. release(result)
  92. result = accountPool.sample()
  93. if not result.isNil and result.isReady(api):
  94. inc result.pending
  95. else:
  96. log "no accounts available for API: " & $api
  97. raise rateLimitError()
  98. proc setRateLimit*(account: GuestAccount; api: Api; remaining, reset: int) =
  99. # avoid undefined behavior in race conditions
  100. if api in account.apis:
  101. let limit = account.apis[api]
  102. if limit.reset >= reset and limit.remaining < remaining:
  103. return
  104. if limit.reset == reset and limit.remaining >= remaining:
  105. account.apis[api].remaining = remaining
  106. return
  107. account.apis[api] = RateLimit(remaining: remaining, reset: reset)
  108. proc initAccountPool*(cfg: Config; accounts: JsonNode) =
  109. enableLogging = cfg.enableDebug
  110. for account in accounts:
  111. accountPool.add GuestAccount(
  112. id: account{"user", "id_str"}.getStr,
  113. oauthToken: account{"oauth_token"}.getStr,
  114. oauthSecret: account{"oauth_token_secret"}.getStr,
  115. )