redis_cache.nim 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. # SPDX-License-Identifier: AGPL-3.0-only
  2. import asyncdispatch, times, strutils, tables, hashes
  3. import redis, redpool, flatty, supersnappy
  4. import types, api
  5. const redisNil = "\0\0"
  6. var
  7. pool {.threadvar.}: RedisPool
  8. baseCacheTime = 60 * 60
  9. rssCacheTime: int
  10. listCacheTime*: int
  11. # flatty can't serialize DateTime, so we need to define this
  12. proc toFlatty*(s: var string, x: DateTime) =
  13. s.toFlatty(x.toTime().toUnix())
  14. proc fromFlatty*(s: string, i: var int, x: var DateTime) =
  15. x = fromUnix(s.fromFlatty(int64)).utc()
  16. proc setCacheTimes*(cfg: Config) =
  17. rssCacheTime = cfg.rssCacheTime * 60
  18. listCacheTime = cfg.listCacheTime * 60
  19. proc migrate*(key, match: string) {.async.} =
  20. pool.withAcquire(r):
  21. let hasKey = await r.get(key)
  22. if hasKey == redisNil:
  23. let list = await r.scan(newCursor(0), match, 100000)
  24. r.startPipelining()
  25. for item in list:
  26. discard await r.del(item)
  27. await r.setk(key, "true")
  28. discard await r.flushPipeline()
  29. proc initRedisPool*(cfg: Config) {.async.} =
  30. try:
  31. pool = await newRedisPool(cfg.redisConns, cfg.redisMaxConns,
  32. host=cfg.redisHost, port=cfg.redisPort,
  33. password=cfg.redisPassword)
  34. await migrate("flatty", "*:*")
  35. await migrate("snappyRss", "rss:*")
  36. await migrate("userBuckets", "p:*")
  37. await migrate("profileDates", "p:*")
  38. pool.withAcquire(r):
  39. # optimize memory usage for profile ID buckets
  40. await r.configSet("hash-max-ziplist-entries", "1000")
  41. except OSError:
  42. stdout.write "Failed to connect to Redis.\n"
  43. stdout.flushFile
  44. quit(1)
  45. template pidKey(name: string): string = "pid:" & $(hash(name) div 1_000_000)
  46. template profileKey(name: string): string = "p:" & name
  47. template listKey(l: List): string = toLower("l:" & l.username & '/' & l.name)
  48. proc get(query: string): Future[string] {.async.} =
  49. pool.withAcquire(r):
  50. result = await r.get(query)
  51. proc setex(key: string; time: int; data: string) {.async.} =
  52. pool.withAcquire(r):
  53. discard await r.setex(key, time, data)
  54. proc cache*(data: List) {.async.} =
  55. await setex(data.listKey, listCacheTime, compress(toFlatty(data)))
  56. proc cache*(data: PhotoRail; name: string) {.async.} =
  57. await setex("pr:" & name, baseCacheTime, compress(toFlatty(data)))
  58. proc cache*(data: Profile) {.async.} =
  59. if data.username.len == 0 or data.id.len == 0: return
  60. let name = toLower(data.username)
  61. pool.withAcquire(r):
  62. r.startPipelining()
  63. discard await r.setex(name.profileKey, baseCacheTime, compress(toFlatty(data)))
  64. discard await r.hset(name.pidKey, name, data.id)
  65. discard await r.flushPipeline()
  66. proc cacheProfileId*(username, id: string) {.async.} =
  67. if username.len == 0 or id.len == 0: return
  68. let name = toLower(username)
  69. pool.withAcquire(r):
  70. discard await r.hset(name.pidKey, name, id)
  71. proc cacheRss*(query: string; rss: Rss) {.async.} =
  72. let key = "rss:" & query
  73. pool.withAcquire(r):
  74. r.startPipelining()
  75. discard await r.hset(key, "rss", rss.feed)
  76. discard await r.hset(key, "min", rss.cursor)
  77. discard await r.expire(key, rssCacheTime)
  78. discard await r.flushPipeline()
  79. proc getProfileId*(username: string): Future[string] {.async.} =
  80. let name = toLower(username)
  81. pool.withAcquire(r):
  82. result = await r.hget(name.pidKey, name)
  83. if result == redisNil:
  84. result.setLen(0)
  85. proc getCachedProfile*(username: string; fetch=true): Future[Profile] {.async.} =
  86. let prof = await get("p:" & toLower(username))
  87. if prof != redisNil:
  88. result = fromFlatty(uncompress(prof), Profile)
  89. elif fetch:
  90. result = await getProfile(username)
  91. proc getCachedPhotoRail*(name: string): Future[PhotoRail] {.async.} =
  92. if name.len == 0: return
  93. let rail = await get("pr:" & toLower(name))
  94. if rail != redisNil:
  95. result = fromFlatty(uncompress(rail), PhotoRail)
  96. else:
  97. result = await getPhotoRail(name)
  98. await cache(result, name)
  99. proc getCachedList*(username=""; name=""; id=""): Future[List] {.async.} =
  100. let list = if id.len > 0: redisNil
  101. else: await get(toLower("l:" & username & '/' & name))
  102. if list != redisNil:
  103. result = fromFlatty(uncompress(list), List)
  104. else:
  105. if id.len > 0:
  106. result = await getGraphListById(id)
  107. else:
  108. result = await getGraphList(username, name)
  109. await cache(result)
  110. proc getCachedRss*(key: string): Future[Rss] {.async.} =
  111. let k = "rss:" & key
  112. pool.withAcquire(r):
  113. result.cursor = await r.hget(k, "min")
  114. if result.cursor.len > 2:
  115. result.feed = await r.hget(k, "rss")
  116. else:
  117. result.cursor.setLen 0