redis_cache.nim 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. # SPDX-License-Identifier: AGPL-3.0-only
  2. import asyncdispatch, times, strformat, strutils, tables, hashes
  3. import redis, redpool, flatty, supersnappy
  4. import types, api
  5. const
  6. redisNil = "\0\0"
  7. baseCacheTime = 60 * 60
  8. var
  9. pool: RedisPool
  10. rssCacheTime: int
  11. listCacheTime*: int
  12. template dawait(future) =
  13. discard await future
  14. # flatty can't serialize DateTime, so we need to define this
  15. proc toFlatty*(s: var string, x: DateTime) =
  16. s.toFlatty(x.toTime().toUnix())
  17. proc fromFlatty*(s: string, i: var int, x: var DateTime) =
  18. var unix: int64
  19. s.fromFlatty(i, unix)
  20. x = fromUnix(unix).utc()
  21. proc setCacheTimes*(cfg: Config) =
  22. rssCacheTime = cfg.rssCacheTime * 60
  23. listCacheTime = cfg.listCacheTime * 60
  24. proc migrate*(key, match: string) {.async.} =
  25. pool.withAcquire(r):
  26. let hasKey = await r.get(key)
  27. if hasKey == redisNil:
  28. let list = await r.scan(newCursor(0), match, 100000)
  29. r.startPipelining()
  30. for item in list:
  31. dawait r.del(item)
  32. await r.setk(key, "true")
  33. dawait r.flushPipeline()
  34. proc initRedisPool*(cfg: Config) {.async.} =
  35. try:
  36. pool = await newRedisPool(cfg.redisConns, cfg.redisMaxConns,
  37. host=cfg.redisHost, port=cfg.redisPort,
  38. password=cfg.redisPassword)
  39. await migrate("flatty", "*:*")
  40. await migrate("snappyRss", "rss:*")
  41. await migrate("userBuckets", "p:*")
  42. await migrate("profileDates", "p:*")
  43. await migrate("profileStats", "p:*")
  44. await migrate("userType", "p:*")
  45. await migrate("verifiedType", "p:*")
  46. pool.withAcquire(r):
  47. # optimize memory usage for user ID buckets
  48. await r.configSet("hash-max-ziplist-entries", "1000")
  49. except OSError:
  50. stdout.write "Failed to connect to Redis.\n"
  51. stdout.flushFile
  52. quit(1)
  53. template uidKey(name: string): string = "pid:" & $(hash(name) div 1_000_000)
  54. template userKey(name: string): string = "p:" & name
  55. template listKey(l: List): string = "l:" & l.id
  56. template tweetKey(id: int64): string = "t:" & $id
  57. proc get(query: string): Future[string] {.async.} =
  58. pool.withAcquire(r):
  59. result = await r.get(query)
  60. proc setEx(key: string; time: int; data: string) {.async.} =
  61. pool.withAcquire(r):
  62. dawait r.setEx(key, time, data)
  63. proc cacheUserId(username, id: string) {.async.} =
  64. if username.len == 0 or id.len == 0: return
  65. let name = toLower(username)
  66. pool.withAcquire(r):
  67. dawait r.hSet(name.uidKey, name, id)
  68. proc cache*(data: List) {.async.} =
  69. await setEx(data.listKey, listCacheTime, compress(toFlatty(data)))
  70. proc cache*(data: PhotoRail; name: string) {.async.} =
  71. await setEx("pr2:" & toLower(name), baseCacheTime * 2, compress(toFlatty(data)))
  72. proc cache*(data: User) {.async.} =
  73. if data.username.len == 0: return
  74. let name = toLower(data.username)
  75. await cacheUserId(name, data.id)
  76. pool.withAcquire(r):
  77. dawait r.setEx(name.userKey, baseCacheTime, compress(toFlatty(data)))
  78. proc cache*(data: Tweet) {.async.} =
  79. if data.isNil or data.id == 0: return
  80. pool.withAcquire(r):
  81. dawait r.setEx(data.id.tweetKey, baseCacheTime, compress(toFlatty(data)))
  82. proc cacheRss*(query: string; rss: Rss) {.async.} =
  83. let key = "rss:" & query
  84. pool.withAcquire(r):
  85. dawait r.hSet(key, "min", rss.cursor)
  86. if rss.cursor != "suspended":
  87. dawait r.hSet(key, "rss", compress(rss.feed))
  88. dawait r.expire(key, rssCacheTime)
  89. template deserialize(data, T) =
  90. try:
  91. result = fromFlatty(uncompress(data), T)
  92. except:
  93. echo "Decompression failed($#): '$#'" % [astToStr(T), data]
  94. proc getUserId*(username: string): Future[string] {.async.} =
  95. let name = toLower(username)
  96. pool.withAcquire(r):
  97. result = await r.hGet(name.uidKey, name)
  98. if result == redisNil:
  99. let user = await getGraphUser(username)
  100. if user.suspended:
  101. return "suspended"
  102. else:
  103. await all(cacheUserId(name, user.id), cache(user))
  104. return user.id
  105. proc getCachedUser*(username: string; fetch=true): Future[User] {.async.} =
  106. let prof = await get("p:" & toLower(username))
  107. if prof != redisNil:
  108. prof.deserialize(User)
  109. elif fetch:
  110. result = await getGraphUser(username)
  111. await cache(result)
  112. proc getCachedUsername*(userId: string): Future[string] {.async.} =
  113. let
  114. key = "i:" & userId
  115. username = await get(key)
  116. if username != redisNil:
  117. result = username
  118. else:
  119. let user = await getGraphUserById(userId)
  120. result = user.username
  121. await setEx(key, baseCacheTime, result)
  122. if result.len > 0 and user.id.len > 0:
  123. await all(cacheUserId(result, user.id), cache(user))
  124. # proc getCachedTweet*(id: int64): Future[Tweet] {.async.} =
  125. # if id == 0: return
  126. # let tweet = await get(id.tweetKey)
  127. # if tweet != redisNil:
  128. # tweet.deserialize(Tweet)
  129. # else:
  130. # result = await getGraphTweetResult($id)
  131. # if not result.isNil:
  132. # await cache(result)
  133. proc getCachedPhotoRail*(id: string): Future[PhotoRail] {.async.} =
  134. if id.len == 0: return
  135. let rail = await get("pr2:" & toLower(id))
  136. if rail != redisNil:
  137. rail.deserialize(PhotoRail)
  138. else:
  139. result = await getPhotoRail(id)
  140. await cache(result, id)
  141. proc getCachedList*(username=""; slug=""; id=""): Future[List] {.async.} =
  142. let list = if id.len == 0: redisNil
  143. else: await get("l:" & id)
  144. if list != redisNil:
  145. list.deserialize(List)
  146. else:
  147. if id.len > 0:
  148. result = await getGraphList(id)
  149. else:
  150. result = await getGraphListBySlug(username, slug)
  151. await cache(result)
  152. proc getCachedRss*(key: string): Future[Rss] {.async.} =
  153. let k = "rss:" & key
  154. pool.withAcquire(r):
  155. result.cursor = await r.hGet(k, "min")
  156. if result.cursor.len > 2:
  157. if result.cursor != "suspended":
  158. let feed = await r.hGet(k, "rss")
  159. if feed.len > 0 and feed != redisNil:
  160. try: result.feed = uncompress feed
  161. except: echo "Decompressing RSS failed: ", feed
  162. else:
  163. result.cursor.setLen 0