auth.nim 5.3 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/session
  5. # max requests at a time per session 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. sessionPool: seq[Session]
  25. enableLogging = false
  26. template log(str: varargs[string, `$`]) =
  27. echo "[sessions] ", str.join("")
  28. proc snowflakeToEpoch(flake: int64): int64 =
  29. int64(((flake shr 22) + 1288834974657) div 1000)
  30. proc getSessionPoolHealth*(): 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 session in sessionPool:
  40. let created = snowflakeToEpoch(session.id)
  41. if created > newest:
  42. newest = created
  43. if created < oldest:
  44. oldest = created
  45. average += created
  46. if session.limited:
  47. limited.incl session.id
  48. for api in session.apis.keys:
  49. let
  50. apiStatus = session.apis[api]
  51. reqs = apiMaxReqs[api] - apiStatus.remaining
  52. # no requests made with this session 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 sessionPool.len > 0:
  58. average = average div sessionPool.len
  59. else:
  60. oldest = 0
  61. average = 0
  62. return %*{
  63. "sessions": %*{
  64. "total": sessionPool.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 getSessionPoolDebug*(): JsonNode =
  76. let now = epochTime().int
  77. var list = newJObject()
  78. for session in sessionPool:
  79. let sessionJson = %*{
  80. "apis": newJObject(),
  81. "pending": session.pending,
  82. }
  83. if session.limited:
  84. sessionJson["limited"] = %true
  85. for api in session.apis.keys:
  86. let
  87. apiStatus = session.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. sessionJson{"apis", $api} = obj
  95. list[$session.id] = sessionJson
  96. return %list
  97. proc rateLimitError*(): ref RateLimitError =
  98. newException(RateLimitError, "rate limited")
  99. proc noSessionsError*(): ref NoSessionsError =
  100. newException(NoSessionsError, "no sessions available")
  101. proc isLimited(session: Session; api: Api): bool =
  102. if session.isNil:
  103. return true
  104. if session.limited and api != Api.userTweets:
  105. if (epochTime().int - session.limitedAt) > dayInSeconds:
  106. session.limited = false
  107. log "resetting limit: ", session.id
  108. return false
  109. else:
  110. return true
  111. if api in session.apis:
  112. let limit = session.apis[api]
  113. return limit.remaining <= 10 and limit.reset > epochTime().int
  114. else:
  115. return false
  116. proc isReady(session: Session; api: Api): bool =
  117. not (session.isNil or session.pending > maxConcurrentReqs or session.isLimited(api))
  118. proc invalidate*(session: var Session) =
  119. if session.isNil: return
  120. log "invalidating: ", session.id
  121. # TODO: This isn't sufficient, but it works for now
  122. let idx = sessionPool.find(session)
  123. if idx > -1: sessionPool.delete(idx)
  124. session = nil
  125. proc release*(session: Session) =
  126. if session.isNil: return
  127. dec session.pending
  128. proc getSession*(api: Api): Future[Session] {.async.} =
  129. for i in 0 ..< sessionPool.len:
  130. if result.isReady(api): break
  131. result = sessionPool.sample()
  132. if not result.isNil and result.isReady(api):
  133. inc result.pending
  134. else:
  135. log "no sessions available for API: ", api
  136. raise noSessionsError()
  137. proc setLimited*(session: Session; api: Api) =
  138. session.limited = true
  139. session.limitedAt = epochTime().int
  140. log "rate limited by api: ", api, ", reqs left: ", session.apis[api].remaining, ", id: ", session.id
  141. proc setRateLimit*(session: Session; api: Api; remaining, reset: int) =
  142. # avoid undefined behavior in race conditions
  143. if api in session.apis:
  144. let limit = session.apis[api]
  145. if limit.reset >= reset and limit.remaining < remaining:
  146. return
  147. if limit.reset == reset and limit.remaining >= remaining:
  148. session.apis[api].remaining = remaining
  149. return
  150. session.apis[api] = RateLimit(remaining: remaining, reset: reset)
  151. proc initSessionPool*(cfg: Config; path: string) =
  152. enableLogging = cfg.enableDebug
  153. if path.endsWith(".json"):
  154. log "ERROR: .json is not supported, the file must be a valid JSONL file ending in .jsonl"
  155. quit 1
  156. if not fileExists(path):
  157. log "ERROR: ", path, " not found. This file is required to authenticate API requests."
  158. quit 1
  159. log "parsing JSONL account sessions file: ", path
  160. for line in path.lines:
  161. sessionPool.add parseSession(line)
  162. log "successfully added ", sessionPool.len, " valid account sessions"