redis_cache.nim 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. pool.withAcquire(r):
  46. # optimize memory usage for user ID buckets
  47. await r.configSet("hash-max-ziplist-entries", "1000")
  48. except OSError:
  49. stdout.write "Failed to connect to Redis.\n"
  50. stdout.flushFile
  51. quit(1)
  52. template uidKey(name: string): string = "pid:" & $(hash(name) div 1_000_000)
  53. template userKey(name: string): string = "p:" & name
  54. template listKey(l: List): string = "l:" & l.id
  55. template tweetKey(id: int64): string = "t:" & $id
  56. proc get(query: string): Future[string] {.async.} =
  57. pool.withAcquire(r):
  58. result = await r.get(query)
  59. proc setEx(key: string; time: int; data: string) {.async.} =
  60. pool.withAcquire(r):
  61. dawait r.setEx(key, time, data)
  62. proc cacheUserId(username, id: string) {.async.} =
  63. if username.len == 0 or id.len == 0: return
  64. let name = toLower(username)
  65. pool.withAcquire(r):
  66. dawait r.hSet(name.uidKey, name, id)
  67. proc cache*(data: List) {.async.} =
  68. await setEx(data.listKey, listCacheTime, compress(toFlatty(data)))
  69. proc cache*(data: PhotoRail; name: string) {.async.} =
  70. await setEx("pr:" & toLower(name), baseCacheTime, compress(toFlatty(data)))
  71. proc cache*(data: User) {.async.} =
  72. if data.username.len == 0: return
  73. let name = toLower(data.username)
  74. await cacheUserId(name, data.id)
  75. pool.withAcquire(r):
  76. dawait r.setEx(name.userKey, baseCacheTime, compress(toFlatty(data)))
  77. proc cache*(data: Tweet) {.async.} =
  78. if data.isNil or data.id == 0: return
  79. pool.withAcquire(r):
  80. dawait r.setEx(data.id.tweetKey, baseCacheTime, compress(toFlatty(data)))
  81. proc cacheRss*(query: string; rss: Rss) {.async.} =
  82. let key = "rss:" & query
  83. pool.withAcquire(r):
  84. dawait r.hSet(key, "min", rss.cursor)
  85. if rss.cursor != "suspended":
  86. dawait r.hSet(key, "rss", compress(rss.feed))
  87. dawait r.expire(key, rssCacheTime)
  88. template deserialize(data, T) =
  89. try:
  90. result = fromFlatty(uncompress(data), T)
  91. except:
  92. echo "Decompression failed($#): '$#'" % [astToStr(T), data]
  93. proc getUserId*(username: string): Future[string] {.async.} =
  94. let name = toLower(username)
  95. pool.withAcquire(r):
  96. result = await r.hGet(name.uidKey, name)
  97. if result == redisNil:
  98. let user = await getUser(username)
  99. if user.suspended:
  100. return "suspended"
  101. else:
  102. await cacheUserId(name, user.id)
  103. return user.id
  104. proc getCachedUser*(username: string; fetch=true): Future[User] {.async.} =
  105. let prof = await get("p:" & toLower(username))
  106. if prof != redisNil:
  107. prof.deserialize(User)
  108. elif fetch:
  109. let userId = await getUserId(username)
  110. result = await getGraphUser(userId)
  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 getUserById(userId)
  120. result = user.username
  121. await setEx(key, baseCacheTime, result)
  122. proc getCachedTweet*(id: int64): Future[Tweet] {.async.} =
  123. if id == 0: return
  124. let tweet = await get(id.tweetKey)
  125. if tweet != redisNil:
  126. tweet.deserialize(Tweet)
  127. else:
  128. result = await getStatus($id)
  129. if result.isNil:
  130. await cache(result)
  131. proc getCachedPhotoRail*(name: string): Future[PhotoRail] {.async.} =
  132. if name.len == 0: return
  133. let rail = await get("pr:" & toLower(name))
  134. if rail != redisNil:
  135. rail.deserialize(PhotoRail)
  136. else:
  137. result = await getPhotoRail(name)
  138. await cache(result, name)
  139. proc getCachedList*(username=""; slug=""; id=""): Future[List] {.async.} =
  140. let list = if id.len == 0: redisNil
  141. else: await get("l:" & id)
  142. if list != redisNil:
  143. list.deserialize(List)
  144. else:
  145. if id.len > 0:
  146. result = await getGraphList(id)
  147. else:
  148. result = await getGraphListBySlug(username, slug)
  149. await cache(result)
  150. proc getCachedRss*(key: string): Future[Rss] {.async.} =
  151. let k = "rss:" & key
  152. pool.withAcquire(r):
  153. result.cursor = await r.hGet(k, "min")
  154. if result.cursor.len > 2:
  155. if result.cursor != "suspended":
  156. let feed = await r.hGet(k, "rss")
  157. if feed.len > 0 and feed != redisNil:
  158. try: result.feed = uncompress feed
  159. except: echo "Decompressing RSS failed: ", feed
  160. else:
  161. result.cursor.setLen 0