tokens.nim 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. #SPDX-License-Identifier: AGPL-3.0-only
  2. import asyncdispatch, times, json, random, strutils, tables, sets, os
  3. import types
  4. import experimental/parser/guestaccount
  5. # max requests at a time per account to avoid race conditions
  6. const
  7. maxConcurrentReqs = 2
  8. dayInSeconds = 24 * 60 * 60
  9. var
  10. accountPool: seq[GuestAccount]
  11. enableLogging = false
  12. template log(str: varargs[string, `$`]) =
  13. if enableLogging: echo "[accounts] ", str.join("")
  14. proc getPoolJson*(): JsonNode =
  15. var
  16. list = newJObject()
  17. totalReqs = 0
  18. totalPending = 0
  19. limited: HashSet[string]
  20. reqsPerApi: Table[string, int]
  21. let now = epochTime().int
  22. for account in accountPool:
  23. totalPending.inc(account.pending)
  24. var includeAccount = false
  25. let accountJson = %*{
  26. "apis": newJObject(),
  27. "pending": account.pending,
  28. }
  29. for api in account.apis.keys:
  30. let
  31. apiStatus = account.apis[api]
  32. obj = %*{}
  33. if apiStatus.reset > now.int:
  34. obj["remaining"] = %apiStatus.remaining
  35. if "remaining" notin obj and not apiStatus.limited:
  36. continue
  37. if apiStatus.limited:
  38. obj["limited"] = %true
  39. limited.incl account.id
  40. accountJson{"apis", $api} = obj
  41. includeAccount = true
  42. let
  43. maxReqs =
  44. case api
  45. of Api.search: 50
  46. of Api.tweetDetail: 150
  47. of Api.photoRail: 180
  48. of Api.userTweets, Api.userTweetsAndReplies, Api.userMedia,
  49. Api.userRestId, Api.userScreenName,
  50. Api.tweetResult,
  51. Api.list, Api.listTweets, Api.listMembers, Api.listBySlug: 500
  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 invalidate*(account: var GuestAccount) =
  81. if account.isNil: return
  82. log "invalidating expired account: ", account.id
  83. # TODO: This isn't sufficient, but it works for now
  84. let idx = accountPool.find(account)
  85. if idx > -1: accountPool.delete(idx)
  86. account = nil
  87. proc release*(account: GuestAccount) =
  88. if account.isNil: return
  89. dec account.pending
  90. proc getGuestAccount*(api: Api): Future[GuestAccount] {.async.} =
  91. for i in 0 ..< accountPool.len:
  92. if result.isReady(api): break
  93. result = accountPool.sample()
  94. if not result.isNil and result.isReady(api):
  95. inc result.pending
  96. else:
  97. log "no accounts available for API: ", api
  98. raise rateLimitError()
  99. proc setLimited*(account: GuestAccount; api: Api) =
  100. account.apis[api].limited = true
  101. account.apis[api].limitedAt = epochTime().int
  102. log "rate limited, api: ", api, ", reqs left: ", account.apis[api].remaining, ", id: ", account.id
  103. proc setRateLimit*(account: GuestAccount; api: Api; remaining, reset: int) =
  104. # avoid undefined behavior in race conditions
  105. if api in account.apis:
  106. let limit = account.apis[api]
  107. if limit.reset >= reset and limit.remaining < remaining:
  108. return
  109. if limit.reset == reset and limit.remaining >= remaining:
  110. account.apis[api].remaining = remaining
  111. return
  112. account.apis[api] = RateLimit(remaining: remaining, reset: reset)
  113. proc initAccountPool*(cfg: Config; path: string) =
  114. enableLogging = cfg.enableDebug
  115. let jsonlPath = if path.endsWith(".json"): (path & 'l') else: path
  116. if fileExists(jsonlPath):
  117. log "Parsing JSONL guest accounts file: ", jsonlPath
  118. for line in jsonlPath.lines:
  119. accountPool.add parseGuestAccount(line)
  120. elif fileExists(path):
  121. log "Parsing JSON guest accounts file: ", path
  122. accountPool = parseGuestAccounts(path)
  123. else:
  124. echo "[accounts] ERROR: ", path, " not found. This file is required to authenticate API requests."
  125. quit 1