tokens.nim 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. of Api.userSearch: 900
  53. reqs = maxReqs - apiStatus.remaining
  54. reqsPerApi[$api] = reqsPerApi.getOrDefault($api, 0) + reqs
  55. totalReqs.inc(reqs)
  56. if includeAccount:
  57. list[account.id] = accountJson
  58. return %*{
  59. "amount": accountPool.len,
  60. "limited": limited.card,
  61. "requests": totalReqs,
  62. "pending": totalPending,
  63. "apis": reqsPerApi,
  64. "accounts": list
  65. }
  66. proc rateLimitError*(): ref RateLimitError =
  67. newException(RateLimitError, "rate limited")
  68. proc isLimited(account: GuestAccount; api: Api): bool =
  69. if account.isNil:
  70. return true
  71. if api in account.apis:
  72. let limit = account.apis[api]
  73. if limit.limited and (epochTime().int - limit.limitedAt) > dayInSeconds:
  74. account.apis[api].limited = false
  75. log "resetting limit, api: ", api, ", id: ", account.id
  76. return limit.limited or (limit.remaining <= 10 and limit.reset > epochTime().int)
  77. else:
  78. return false
  79. proc isReady(account: GuestAccount; api: Api): bool =
  80. not (account.isNil or account.pending > maxConcurrentReqs or account.isLimited(api))
  81. proc invalidate*(account: var GuestAccount) =
  82. if account.isNil: return
  83. log "invalidating expired account: ", account.id
  84. # TODO: This isn't sufficient, but it works for now
  85. let idx = accountPool.find(account)
  86. if idx > -1: accountPool.delete(idx)
  87. account = nil
  88. proc release*(account: GuestAccount) =
  89. if account.isNil: return
  90. dec account.pending
  91. proc getGuestAccount*(api: Api): Future[GuestAccount] {.async.} =
  92. for i in 0 ..< accountPool.len:
  93. if result.isReady(api): break
  94. result = accountPool.sample()
  95. if not result.isNil and result.isReady(api):
  96. inc result.pending
  97. else:
  98. log "no accounts available for API: ", api
  99. raise rateLimitError()
  100. proc setLimited*(account: GuestAccount; api: Api) =
  101. account.apis[api].limited = true
  102. account.apis[api].limitedAt = epochTime().int
  103. log "rate limited, api: ", api, ", reqs left: ", account.apis[api].remaining, ", id: ", account.id
  104. proc setRateLimit*(account: GuestAccount; api: Api; remaining, reset: int) =
  105. # avoid undefined behavior in race conditions
  106. if api in account.apis:
  107. let limit = account.apis[api]
  108. if limit.reset >= reset and limit.remaining < remaining:
  109. return
  110. if limit.reset == reset and limit.remaining >= remaining:
  111. account.apis[api].remaining = remaining
  112. return
  113. account.apis[api] = RateLimit(remaining: remaining, reset: reset)
  114. proc initAccountPool*(cfg: Config; path: string) =
  115. enableLogging = cfg.enableDebug
  116. let jsonlPath = if path.endsWith(".json"): (path & 'l') else: path
  117. if fileExists(jsonlPath):
  118. log "Parsing JSONL guest accounts file: ", jsonlPath
  119. for line in jsonlPath.lines:
  120. accountPool.add parseGuestAccount(line)
  121. elif fileExists(path):
  122. log "Parsing JSON guest accounts file: ", path
  123. accountPool = parseGuestAccounts(path)
  124. else:
  125. echo "[accounts] ERROR: ", path, " not found. This file is required to authenticate API requests."
  126. quit 1