Line data Source code
1 4 : (ns matchscore.domain.user.repository.redis
2 : (:require
3 : [matchscore.db.redis.core :as db-redis-core]
4 : [matchscore.domain.user.entity :as entity]
5 : [taoensso.carmine :as car]))
6 :
7 :
8 8 : (def ^:private cache-key "users")
9 :
10 :
11 8 : (def ^:private tg-uuid-map-key "tg-uuid-map")
12 :
13 :
14 4 : (defprotocol
15 : RedisUserRepository
16 : (get-all-cached
17 : [this]
18 : "Returns users from Redis or nil on miss.")
19 : (cache-all!
20 : [this users]
21 : "Stores users in Redis.")
22 : (get-uuid-by-telegram-id
23 : [this telegram-id]
24 : "Returns uuid from Redis hash or nil.")
25 : (cache-uuid-by-telegram-id!
26 : [this telegram-id uuid]
27 : "Stores telegram-id -> uuid mapping in Redis hash.")
28 : (invalidate-users!
29 : [this]
30 : "Deletes users cache key.")
31 : (invalidate-tg-uuid!
32 : [this telegram-id]
33 : "Deletes specific hash entry from tg-uuid-map."))
34 :
35 :
36 4 : (defrecord
37 : RedisUserRepo
38 : [redis]
39 : RedisUserRepository
40 :
41 : (get-all-cached
42 : [_]
43 15 : (let [result (db-redis-core/retrieve-objects redis cache-key)]
44 32 : (when (= (:status result) :ok) (mapv entity/make-user (:data result)))))
45 :
46 : (cache-all!
47 : [_ users]
48 36 : (when (seq users) (db-redis-core/store-objects redis cache-key (vec users))))
49 :
50 : (get-uuid-by-telegram-id
51 : [_ telegram-id]
52 172 : (let [cached (car/wcar redis (car/hget tg-uuid-map-key (str telegram-id)))]
53 22 : (when (some? cached) cached)))
54 :
55 : (cache-uuid-by-telegram-id!
56 : [_ telegram-id uuid]
57 172 : (car/wcar redis (car/hset tg-uuid-map-key (str telegram-id) uuid)))
58 :
59 117 : (invalidate-users! [_] (car/wcar redis (car/del cache-key)))
60 :
61 : (invalidate-tg-uuid!
62 : [_ telegram-id]
63 126 : (car/wcar redis (car/hdel tg-uuid-map-key (str telegram-id)))))
64 :
65 :
66 4 : (defn make-repository
67 : "Creates a RedisUserRepo."
68 : [redis]
69 12 : (->RedisUserRepo redis))
|