auth.nim 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. #SPDX-License-Identifier: AGPL-3.0-only
  2. import std/[asyncdispatch, times, json, random, sequtils, strutils, tables, packedsets, 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. apiMaxReqs: Table[Api, int] = {
  10. Api.search: 50,
  11. Api.tweetDetail: 500,
  12. Api.userTweets: 500,
  13. Api.userTweetsAndReplies: 500,
  14. Api.userMedia: 500,
  15. Api.userRestId: 500,
  16. Api.userScreenName: 500,
  17. Api.tweetResult: 500,
  18. Api.list: 500,
  19. Api.listTweets: 500,
  20. Api.listMembers: 500,
  21. Api.listBySlug: 500
  22. }.toTable
  23. var
  24. accountPool: seq[GuestAccount]
  25. enableLogging = false
  26. template log(str: varargs[string, `$`]) =
  27. if enableLogging: echo "[accounts] ", str.join("")
  28. proc snowflakeToEpoch(flake: int64): int64 =
  29. int64(((flake shr 22) + 1288834974657) div 1000)
  30. proc getAccountPoolHealth*(): JsonNode =
  31. let now = epochTime().int
  32. var
  33. totalReqs = 0
  34. limited: PackedSet[int64]
  35. reqsPerApi: Table[string, int]
  36. oldest = now.int64
  37. newest = 0'i64
  38. average = 0'i64
  39. for account in accountPool:
  40. let created = snowflakeToEpoch(account.id)
  41. if created > newest:
  42. newest = created
  43. if created < oldest:
  44. oldest = created
  45. average += created
  46. if account.limited:
  47. limited.incl account.id
  48. for api in account.apis.keys:
  49. let
  50. apiStatus = account.apis[api]
  51. reqs = apiMaxReqs[api] - apiStatus.remaining
  52. # no requests made with this account and endpoint since the limit reset
  53. if apiStatus.reset < now:
  54. continue
  55. reqsPerApi.mgetOrPut($api, 0).inc reqs
  56. totalReqs.inc reqs
  57. if accountPool.len > 0:
  58. average = average div accountPool.len
  59. else:
  60. oldest = 0
  61. average = 0
  62. return %*{
  63. "accounts": %*{
  64. "total": accountPool.len,
  65. "limited": limited.card,
  66. "oldest": $fromUnix(oldest),
  67. "newest": $fromUnix(newest),
  68. "average": $fromUnix(average)
  69. },
  70. "requests": %*{
  71. "total": totalReqs,
  72. "apis": reqsPerApi
  73. }
  74. }
  75. proc getAccountPoolDebug*(): JsonNode =
  76. let now = epochTime().int
  77. var list = newJObject()
  78. for account in accountPool:
  79. let accountJson = %*{
  80. "apis": newJObject(),
  81. "pending": account.pending,
  82. }
  83. if account.limited:
  84. accountJson["limited"] = %true
  85. for api in account.apis.keys:
  86. let
  87. apiStatus = account.apis[api]
  88. obj = %*{}
  89. if apiStatus.reset > now.int:
  90. obj["remaining"] = %apiStatus.remaining
  91. obj["reset"] = %apiStatus.reset
  92. if "remaining" notin obj:
  93. continue
  94. accountJson{"apis", $api} = obj
  95. list[$account.id] = accountJson
  96. return %list
  97. proc rateLimitError*(): ref RateLimitError =
  98. newException(RateLimitError, "rate limited")
  99. proc noAccountsError*(): ref NoAccountsError =
  100. newException(NoAccountsError, "no accounts available")
  101. proc isLimited(account: GuestAccount; api: Api): bool =
  102. if account.isNil:
  103. return true
  104. if account.limited and api != Api.userTweets:
  105. if (epochTime().int - account.limitedAt) > dayInSeconds:
  106. account.limited = false
  107. log "resetting limit: ", account.id
  108. else:
  109. return false
  110. if api in account.apis:
  111. let limit = account.apis[api]
  112. return limit.remaining <= 10 and limit.reset > epochTime().int
  113. else:
  114. return false
  115. proc isReady(account: GuestAccount; api: Api): bool =
  116. not (account.isNil or account.pending > maxConcurrentReqs or account.isLimited(api))
  117. proc invalidate*(account: var GuestAccount) =
  118. if account.isNil: return
  119. log "invalidating: ", account.id
  120. # TODO: This isn't sufficient, but it works for now
  121. let idx = accountPool.find(account)
  122. if idx > -1: accountPool.delete(idx)
  123. account = nil
  124. proc release*(account: GuestAccount) =
  125. if account.isNil: return
  126. dec account.pending
  127. proc getGuestAccount*(api: Api): Future[GuestAccount] {.async.} =
  128. for i in 0 ..< accountPool.len:
  129. if result.isReady(api): break
  130. result = accountPool.sample()
  131. if not result.isNil and result.isReady(api):
  132. inc result.pending
  133. else:
  134. log "no accounts available for API: ", api
  135. raise noAccountsError()
  136. proc setLimited*(account: GuestAccount; api: Api) =
  137. account.limited = true
  138. account.limitedAt = epochTime().int
  139. log "rate limited by api: ", api, ", reqs left: ", account.apis[api].remaining, ", id: ", account.id
  140. proc setRateLimit*(account: GuestAccount; api: Api; remaining, reset: int) =
  141. # avoid undefined behavior in race conditions
  142. if api in account.apis:
  143. let limit = account.apis[api]
  144. if limit.reset >= reset and limit.remaining < remaining:
  145. return
  146. if limit.reset == reset and limit.remaining >= remaining:
  147. account.apis[api].remaining = remaining
  148. return
  149. account.apis[api] = RateLimit(remaining: remaining, reset: reset)
  150. proc initAccountPool*(cfg: Config; path: string) =
  151. enableLogging = cfg.enableDebug
  152. let jsonlPath = if path.endsWith(".json"): (path & 'l') else: path
  153. if fileExists(jsonlPath):
  154. log "Parsing JSONL guest accounts file: ", jsonlPath
  155. for line in jsonlPath.lines:
  156. accountPool.add parseGuestAccount(line)
  157. elif fileExists(path):
  158. log "Parsing JSON guest accounts file: ", path
  159. accountPool = parseGuestAccounts(path)
  160. else:
  161. echo "[accounts] ERROR: ", path, " not found. This file is required to authenticate API requests."
  162. quit 1
  163. log "Successfully added ", accountPool.len, " valid accounts."