Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

redis_conn.py 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. #
  2. # Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import logging
  17. import json
  18. import valkey as redis
  19. from rag import settings
  20. from rag.utils import singleton
  21. class Payload:
  22. def __init__(self, consumer, queue_name, group_name, msg_id, message):
  23. self.__consumer = consumer
  24. self.__queue_name = queue_name
  25. self.__group_name = group_name
  26. self.__msg_id = msg_id
  27. self.__message = json.loads(message["message"])
  28. def ack(self):
  29. try:
  30. self.__consumer.xack(self.__queue_name, self.__group_name, self.__msg_id)
  31. return True
  32. except Exception as e:
  33. logging.warning("[EXCEPTION]ack" + str(self.__queue_name) + "||" + str(e))
  34. return False
  35. def get_message(self):
  36. return self.__message
  37. @singleton
  38. class RedisDB:
  39. def __init__(self):
  40. self.REDIS = None
  41. self.config = settings.REDIS
  42. self.__open__()
  43. def __open__(self):
  44. try:
  45. self.REDIS = redis.StrictRedis(
  46. host=self.config["host"].split(":")[0],
  47. port=int(self.config.get("host", ":6379").split(":")[1]),
  48. db=int(self.config.get("db", 1)),
  49. password=self.config.get("password"),
  50. decode_responses=True,
  51. )
  52. except Exception:
  53. logging.warning("Redis can't be connected.")
  54. return self.REDIS
  55. def health(self):
  56. self.REDIS.ping()
  57. a, b = "xx", "yy"
  58. self.REDIS.set(a, b, 3)
  59. if self.REDIS.get(a) == b:
  60. return True
  61. def is_alive(self):
  62. return self.REDIS is not None
  63. def exist(self, k):
  64. if not self.REDIS:
  65. return
  66. try:
  67. return self.REDIS.exists(k)
  68. except Exception as e:
  69. logging.warning("RedisDB.exist " + str(k) + " got exception: " + str(e))
  70. self.__open__()
  71. def get(self, k):
  72. if not self.REDIS:
  73. return
  74. try:
  75. return self.REDIS.get(k)
  76. except Exception as e:
  77. logging.warning("RedisDB.get " + str(k) + " got exception: " + str(e))
  78. self.__open__()
  79. def set_obj(self, k, obj, exp=3600):
  80. try:
  81. self.REDIS.set(k, json.dumps(obj, ensure_ascii=False), exp)
  82. return True
  83. except Exception as e:
  84. logging.warning("RedisDB.set_obj " + str(k) + " got exception: " + str(e))
  85. self.__open__()
  86. return False
  87. def set(self, k, v, exp=3600):
  88. try:
  89. self.REDIS.set(k, v, exp)
  90. return True
  91. except Exception as e:
  92. logging.warning("RedisDB.set " + str(k) + " got exception: " + str(e))
  93. self.__open__()
  94. return False
  95. def sadd(self, key: str, member: str):
  96. try:
  97. self.REDIS.sadd(key, member)
  98. return True
  99. except Exception as e:
  100. logging.warning("RedisDB.sadd " + str(key) + " got exception: " + str(e))
  101. self.__open__()
  102. return False
  103. def srem(self, key: str, member: str):
  104. try:
  105. self.REDIS.srem(key, member)
  106. return True
  107. except Exception as e:
  108. logging.warning("RedisDB.srem " + str(key) + " got exception: " + str(e))
  109. self.__open__()
  110. return False
  111. def smembers(self, key: str):
  112. try:
  113. res = self.REDIS.smembers(key)
  114. return res
  115. except Exception as e:
  116. logging.warning(
  117. "RedisDB.smembers " + str(key) + " got exception: " + str(e)
  118. )
  119. self.__open__()
  120. return None
  121. def zadd(self, key: str, member: str, score: float):
  122. try:
  123. self.REDIS.zadd(key, {member: score})
  124. return True
  125. except Exception as e:
  126. logging.warning("RedisDB.zadd " + str(key) + " got exception: " + str(e))
  127. self.__open__()
  128. return False
  129. def zcount(self, key: str, min: float, max: float):
  130. try:
  131. res = self.REDIS.zcount(key, min, max)
  132. return res
  133. except Exception as e:
  134. logging.warning("RedisDB.zcount " + str(key) + " got exception: " + str(e))
  135. self.__open__()
  136. return 0
  137. def zpopmin(self, key: str, count: int):
  138. try:
  139. res = self.REDIS.zpopmin(key, count)
  140. return res
  141. except Exception as e:
  142. logging.warning("RedisDB.zpopmin " + str(key) + " got exception: " + str(e))
  143. self.__open__()
  144. return None
  145. def zrangebyscore(self, key: str, min: float, max: float):
  146. try:
  147. res = self.REDIS.zrangebyscore(key, min, max)
  148. return res
  149. except Exception as e:
  150. logging.warning(
  151. "RedisDB.zrangebyscore " + str(key) + " got exception: " + str(e)
  152. )
  153. self.__open__()
  154. return None
  155. def transaction(self, key, value, exp=3600):
  156. try:
  157. pipeline = self.REDIS.pipeline(transaction=True)
  158. pipeline.set(key, value, exp, nx=True)
  159. pipeline.execute()
  160. return True
  161. except Exception as e:
  162. logging.warning(
  163. "RedisDB.transaction " + str(key) + " got exception: " + str(e)
  164. )
  165. self.__open__()
  166. return False
  167. def queue_product(self, queue, message, exp=settings.SVR_QUEUE_RETENTION) -> bool:
  168. for _ in range(3):
  169. try:
  170. payload = {"message": json.dumps(message)}
  171. pipeline = self.REDIS.pipeline()
  172. pipeline.xadd(queue, payload)
  173. # pipeline.expire(queue, exp)
  174. pipeline.execute()
  175. return True
  176. except Exception as e:
  177. logging.exception(
  178. "RedisDB.queue_product " + str(queue) + " got exception: " + str(e)
  179. )
  180. return False
  181. def queue_consumer(
  182. self, queue_name, group_name, consumer_name, msg_id=b">"
  183. ) -> Payload:
  184. try:
  185. group_info = self.REDIS.xinfo_groups(queue_name)
  186. if not any(e["name"] == group_name for e in group_info):
  187. self.REDIS.xgroup_create(queue_name, group_name, id="0", mkstream=True)
  188. args = {
  189. "groupname": group_name,
  190. "consumername": consumer_name,
  191. "count": 1,
  192. "block": 10000,
  193. "streams": {queue_name: msg_id},
  194. }
  195. messages = self.REDIS.xreadgroup(**args)
  196. if not messages:
  197. return None
  198. stream, element_list = messages[0]
  199. msg_id, payload = element_list[0]
  200. res = Payload(self.REDIS, queue_name, group_name, msg_id, payload)
  201. return res
  202. except Exception as e:
  203. if "key" in str(e):
  204. pass
  205. else:
  206. logging.exception(
  207. "RedisDB.queue_consumer "
  208. + str(queue_name)
  209. + " got exception: "
  210. + str(e)
  211. )
  212. return None
  213. def get_unacked_for(self, consumer_name, queue_name, group_name):
  214. try:
  215. group_info = self.REDIS.xinfo_groups(queue_name)
  216. if not any(e["name"] == group_name for e in group_info):
  217. return
  218. pendings = self.REDIS.xpending_range(
  219. queue_name,
  220. group_name,
  221. min=0,
  222. max=10000000000000,
  223. count=1,
  224. consumername=consumer_name,
  225. )
  226. if not pendings:
  227. return
  228. msg_id = pendings[0]["message_id"]
  229. msg = self.REDIS.xrange(queue_name, min=msg_id, count=1)
  230. _, payload = msg[0]
  231. return Payload(self.REDIS, queue_name, group_name, msg_id, payload)
  232. except Exception as e:
  233. if "key" in str(e):
  234. return
  235. logging.exception(
  236. "RedisDB.get_unacked_for " + consumer_name + " got exception: " + str(e)
  237. )
  238. self.__open__()
  239. def queue_info(self, queue, group_name) -> dict | None:
  240. try:
  241. groups = self.REDIS.xinfo_groups(queue)
  242. for group in groups:
  243. if group["name"] == group_name:
  244. return group
  245. except Exception as e:
  246. logging.warning(
  247. "RedisDB.queue_info " + str(queue) + " got exception: " + str(e)
  248. )
  249. return None
  250. REDIS_CONN = RedisDB()