main.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import asyncio
  2. import socketio
  3. import logging
  4. import sys
  5. import time
  6. from redis.sentinel import Sentinel
  7. from open_webui.models.users import Users, UserNameResponse
  8. from open_webui.models.channels import Channels
  9. from open_webui.models.chats import Chats
  10. from open_webui.env import (
  11. ENABLE_WEBSOCKET_SUPPORT,
  12. WEBSOCKET_MANAGER,
  13. WEBSOCKET_REDIS_URL,
  14. WEBSOCKET_REDIS_LOCK_TIMEOUT,
  15. WEBSOCKET_SENTINEL_PORT,
  16. WEBSOCKET_SENTINEL_HOSTS,
  17. )
  18. from open_webui.utils.auth import decode_token
  19. from open_webui.socket.utils import RedisDict, RedisLock, parse_redis_sentinel_url
  20. from open_webui.env import (
  21. GLOBAL_LOG_LEVEL,
  22. SRC_LOG_LEVELS,
  23. )
  24. class AsyncRedisSentinelManager(socketio.AsyncRedisManager):
  25. def __init__(self, sentinel_hosts, sentinel_port=26379, redis_port=6379, service_name="mymaster", db=0,
  26. username=None, password=None, channel='socketio', write_only=False, **kwargs):
  27. """
  28. Initialize the Redis Sentinel Manager.
  29. :param sentinel_hosts: List of Sentinel hosts
  30. :param sentinel_port: Sentinel Port
  31. :param redis_port: Redis Port
  32. :param service_name: Master service name in Sentinel
  33. :param db: Redis database to use
  34. :param username: Redis username (if any)
  35. :param password: Redis password (if any)
  36. :param channel: The Redis channel name
  37. :param write_only: If set to True, only initialize the connection to send messages
  38. :param kwargs: Additional connection arguments for Redis
  39. """
  40. self.sentinel_addresses = [(host, sentinel_port) for host in sentinel_hosts]
  41. self.redis_port=redis_port
  42. self.service_name = service_name
  43. self.db = db
  44. self.username = username
  45. self.password = password
  46. self.channel = channel
  47. self.write_only = write_only
  48. self.redis_kwargs = kwargs
  49. # Skip parent's init but call grandparent's init
  50. socketio.AsyncManager.__init__(self)
  51. self._redis_connect()
  52. def _redis_connect(self):
  53. """Establish connections to Redis through Sentinel."""
  54. sentinel = redis.sentinel.Sentinel(
  55. self.sentinel_addresses,
  56. port=self.redis_port,
  57. db=self.db,
  58. username=self.username,
  59. password=self.password,
  60. **self.redis_kwargs
  61. )
  62. # Get connections to the Redis master and slave
  63. self.redis = sentinel.master_for(self.service_name)
  64. if not self.write_only:
  65. self.pubsub = sentinel.slave_for(self.service_name).pubsub()
  66. self.pubsub.subscribe(self.channel)
  67. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  68. log = logging.getLogger(__name__)
  69. log.setLevel(SRC_LOG_LEVELS["SOCKET"])
  70. if WEBSOCKET_MANAGER == "redis":
  71. if WEBSOCKET_SENTINEL_HOSTS:
  72. redis_config = parse_redis_sentinel_url(WEBSOCKET_REDIS_URL)
  73. mgr = AsyncRedisSentinelManager(WEBSOCKET_SENTINEL_HOSTS.split(','), sentinel_port=int(WEBSOCKET_SENTINEL_PORT), redis_port=redis_config["port"],
  74. service=redis_config["service"], db=redis_config["db"], username=redis_config["username"], password=redis_config["password"])
  75. else:
  76. mgr = socketio.AsyncRedisManager(WEBSOCKET_REDIS_URL)
  77. sio = socketio.AsyncServer(
  78. cors_allowed_origins=[],
  79. async_mode="asgi",
  80. transports=(["websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]),
  81. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  82. always_connect=True,
  83. client_manager=mgr,
  84. )
  85. else:
  86. sio = socketio.AsyncServer(
  87. cors_allowed_origins=[],
  88. async_mode="asgi",
  89. transports=(["websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]),
  90. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  91. always_connect=True,
  92. )
  93. # Timeout duration in seconds
  94. TIMEOUT_DURATION = 3
  95. # Dictionary to maintain the user pool
  96. if WEBSOCKET_MANAGER == "redis":
  97. log.debug("Using Redis to manage websockets.")
  98. sentinel_hosts=WEBSOCKET_SENTINEL_HOSTS.split(',')
  99. sentinel_port=int(WEBSOCKET_SENTINEL_PORT)
  100. sentinels=[(host, sentinel_port) for host in sentinel_hosts]
  101. SESSION_POOL = RedisDict("open-webui:session_pool", redis_url=WEBSOCKET_REDIS_URL, sentinels)
  102. USER_POOL = RedisDict("open-webui:user_pool", redis_url=WEBSOCKET_REDIS_URL, sentinels)
  103. USAGE_POOL = RedisDict("open-webui:usage_pool", redis_url=WEBSOCKET_REDIS_URL, sentinels)
  104. clean_up_lock = RedisLock(
  105. redis_url=WEBSOCKET_REDIS_URL,
  106. lock_name="usage_cleanup_lock",
  107. timeout_secs=WEBSOCKET_REDIS_LOCK_TIMEOUT,
  108. sentinels,
  109. )
  110. aquire_func = clean_up_lock.aquire_lock
  111. renew_func = clean_up_lock.renew_lock
  112. release_func = clean_up_lock.release_lock
  113. else:
  114. SESSION_POOL = {}
  115. USER_POOL = {}
  116. USAGE_POOL = {}
  117. aquire_func = release_func = renew_func = lambda: True
  118. async def periodic_usage_pool_cleanup():
  119. if not aquire_func():
  120. log.debug("Usage pool cleanup lock already exists. Not running it.")
  121. return
  122. log.debug("Running periodic_usage_pool_cleanup")
  123. try:
  124. while True:
  125. if not renew_func():
  126. log.error(f"Unable to renew cleanup lock. Exiting usage pool cleanup.")
  127. raise Exception("Unable to renew usage pool cleanup lock.")
  128. now = int(time.time())
  129. send_usage = False
  130. for model_id, connections in list(USAGE_POOL.items()):
  131. # Creating a list of sids to remove if they have timed out
  132. expired_sids = [
  133. sid
  134. for sid, details in connections.items()
  135. if now - details["updated_at"] > TIMEOUT_DURATION
  136. ]
  137. for sid in expired_sids:
  138. del connections[sid]
  139. if not connections:
  140. log.debug(f"Cleaning up model {model_id} from usage pool")
  141. del USAGE_POOL[model_id]
  142. else:
  143. USAGE_POOL[model_id] = connections
  144. send_usage = True
  145. if send_usage:
  146. # Emit updated usage information after cleaning
  147. await sio.emit("usage", {"models": get_models_in_use()})
  148. await asyncio.sleep(TIMEOUT_DURATION)
  149. finally:
  150. release_func()
  151. app = socketio.ASGIApp(
  152. sio,
  153. socketio_path="/ws/socket.io",
  154. )
  155. def get_models_in_use():
  156. # List models that are currently in use
  157. models_in_use = list(USAGE_POOL.keys())
  158. return models_in_use
  159. @sio.on("usage")
  160. async def usage(sid, data):
  161. model_id = data["model"]
  162. # Record the timestamp for the last update
  163. current_time = int(time.time())
  164. # Store the new usage data and task
  165. USAGE_POOL[model_id] = {
  166. **(USAGE_POOL[model_id] if model_id in USAGE_POOL else {}),
  167. sid: {"updated_at": current_time},
  168. }
  169. # Broadcast the usage data to all clients
  170. await sio.emit("usage", {"models": get_models_in_use()})
  171. @sio.event
  172. async def connect(sid, environ, auth):
  173. user = None
  174. if auth and "token" in auth:
  175. data = decode_token(auth["token"])
  176. if data is not None and "id" in data:
  177. user = Users.get_user_by_id(data["id"])
  178. if user:
  179. SESSION_POOL[sid] = user.model_dump()
  180. if user.id in USER_POOL:
  181. USER_POOL[user.id] = USER_POOL[user.id] + [sid]
  182. else:
  183. USER_POOL[user.id] = [sid]
  184. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  185. await sio.emit("user-list", {"user_ids": list(USER_POOL.keys())})
  186. await sio.emit("usage", {"models": get_models_in_use()})
  187. @sio.on("user-join")
  188. async def user_join(sid, data):
  189. auth = data["auth"] if "auth" in data else None
  190. if not auth or "token" not in auth:
  191. return
  192. data = decode_token(auth["token"])
  193. if data is None or "id" not in data:
  194. return
  195. user = Users.get_user_by_id(data["id"])
  196. if not user:
  197. return
  198. SESSION_POOL[sid] = user.model_dump()
  199. if user.id in USER_POOL:
  200. USER_POOL[user.id] = USER_POOL[user.id] + [sid]
  201. else:
  202. USER_POOL[user.id] = [sid]
  203. # Join all the channels
  204. channels = Channels.get_channels_by_user_id(user.id)
  205. log.debug(f"{channels=}")
  206. for channel in channels:
  207. await sio.enter_room(sid, f"channel:{channel.id}")
  208. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  209. await sio.emit("user-list", {"user_ids": list(USER_POOL.keys())})
  210. return {"id": user.id, "name": user.name}
  211. @sio.on("join-channels")
  212. async def join_channel(sid, data):
  213. auth = data["auth"] if "auth" in data else None
  214. if not auth or "token" not in auth:
  215. return
  216. data = decode_token(auth["token"])
  217. if data is None or "id" not in data:
  218. return
  219. user = Users.get_user_by_id(data["id"])
  220. if not user:
  221. return
  222. # Join all the channels
  223. channels = Channels.get_channels_by_user_id(user.id)
  224. log.debug(f"{channels=}")
  225. for channel in channels:
  226. await sio.enter_room(sid, f"channel:{channel.id}")
  227. @sio.on("channel-events")
  228. async def channel_events(sid, data):
  229. room = f"channel:{data['channel_id']}"
  230. participants = sio.manager.get_participants(
  231. namespace="/",
  232. room=room,
  233. )
  234. sids = [sid for sid, _ in participants]
  235. if sid not in sids:
  236. return
  237. event_data = data["data"]
  238. event_type = event_data["type"]
  239. if event_type == "typing":
  240. await sio.emit(
  241. "channel-events",
  242. {
  243. "channel_id": data["channel_id"],
  244. "message_id": data.get("message_id", None),
  245. "data": event_data,
  246. "user": UserNameResponse(**SESSION_POOL[sid]).model_dump(),
  247. },
  248. room=room,
  249. )
  250. @sio.on("user-list")
  251. async def user_list(sid):
  252. await sio.emit("user-list", {"user_ids": list(USER_POOL.keys())})
  253. @sio.event
  254. async def disconnect(sid):
  255. if sid in SESSION_POOL:
  256. user = SESSION_POOL[sid]
  257. del SESSION_POOL[sid]
  258. user_id = user["id"]
  259. USER_POOL[user_id] = [_sid for _sid in USER_POOL[user_id] if _sid != sid]
  260. if len(USER_POOL[user_id]) == 0:
  261. del USER_POOL[user_id]
  262. await sio.emit("user-list", {"user_ids": list(USER_POOL.keys())})
  263. else:
  264. pass
  265. # print(f"Unknown session ID {sid} disconnected")
  266. def get_event_emitter(request_info):
  267. async def __event_emitter__(event_data):
  268. user_id = request_info["user_id"]
  269. session_ids = list(
  270. set(USER_POOL.get(user_id, []) + [request_info["session_id"]])
  271. )
  272. for session_id in session_ids:
  273. await sio.emit(
  274. "chat-events",
  275. {
  276. "chat_id": request_info.get("chat_id", None),
  277. "message_id": request_info.get("message_id", None),
  278. "data": event_data,
  279. },
  280. to=session_id,
  281. )
  282. if "type" in event_data and event_data["type"] == "status":
  283. Chats.add_message_status_to_chat_by_id_and_message_id(
  284. request_info["chat_id"],
  285. request_info["message_id"],
  286. event_data.get("data", {}),
  287. )
  288. if "type" in event_data and event_data["type"] == "message":
  289. message = Chats.get_message_by_id_and_message_id(
  290. request_info["chat_id"],
  291. request_info["message_id"],
  292. )
  293. content = message.get("content", "")
  294. content += event_data.get("data", {}).get("content", "")
  295. Chats.upsert_message_to_chat_by_id_and_message_id(
  296. request_info["chat_id"],
  297. request_info["message_id"],
  298. {
  299. "content": content,
  300. },
  301. )
  302. if "type" in event_data and event_data["type"] == "replace":
  303. content = event_data.get("data", {}).get("content", "")
  304. Chats.upsert_message_to_chat_by_id_and_message_id(
  305. request_info["chat_id"],
  306. request_info["message_id"],
  307. {
  308. "content": content,
  309. },
  310. )
  311. return __event_emitter__
  312. def get_event_call(request_info):
  313. async def __event_caller__(event_data):
  314. response = await sio.call(
  315. "chat-events",
  316. {
  317. "chat_id": request_info.get("chat_id", None),
  318. "message_id": request_info.get("message_id", None),
  319. "data": event_data,
  320. },
  321. to=request_info["session_id"],
  322. )
  323. return response
  324. return __event_caller__
  325. get_event_caller = get_event_call
  326. def get_user_id_from_session_pool(sid):
  327. user = SESSION_POOL.get(sid)
  328. if user:
  329. return user["id"]
  330. return None
  331. def get_user_ids_from_room(room):
  332. active_session_ids = sio.manager.get_participants(
  333. namespace="/",
  334. room=room,
  335. )
  336. active_user_ids = list(
  337. set(
  338. [SESSION_POOL.get(session_id[0])["id"] for session_id in active_session_ids]
  339. )
  340. )
  341. return active_user_ids
  342. def get_active_status_by_user_id(user_id):
  343. if user_id in USER_POOL:
  344. return True
  345. return False