main.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. import asyncio
  2. import socketio
  3. import logging
  4. import sys
  5. import time
  6. from open_webui.models.users import Users, UserNameResponse
  7. from open_webui.models.channels import Channels
  8. from open_webui.models.chats import Chats
  9. from open_webui.env import (
  10. ENABLE_WEBSOCKET_SUPPORT,
  11. WEBSOCKET_MANAGER,
  12. WEBSOCKET_REDIS_URL,
  13. )
  14. from open_webui.utils.auth import decode_token
  15. from open_webui.socket.utils import RedisDict, RedisLock
  16. from open_webui.env import (
  17. GLOBAL_LOG_LEVEL,
  18. SRC_LOG_LEVELS,
  19. )
  20. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  21. log = logging.getLogger(__name__)
  22. log.setLevel(SRC_LOG_LEVELS["SOCKET"])
  23. if WEBSOCKET_MANAGER == "redis":
  24. mgr = socketio.AsyncRedisManager(WEBSOCKET_REDIS_URL)
  25. sio = socketio.AsyncServer(
  26. cors_allowed_origins=[],
  27. async_mode="asgi",
  28. transports=(["websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]),
  29. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  30. always_connect=True,
  31. client_manager=mgr,
  32. )
  33. else:
  34. sio = socketio.AsyncServer(
  35. cors_allowed_origins=[],
  36. async_mode="asgi",
  37. transports=(["websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]),
  38. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  39. always_connect=True,
  40. )
  41. # Timeout duration in seconds
  42. TIMEOUT_DURATION = 3
  43. # Dictionary to maintain the user pool
  44. if WEBSOCKET_MANAGER == "redis":
  45. log.debug("Using Redis to manage websockets.")
  46. SESSION_POOL = RedisDict("open-webui:session_pool", redis_url=WEBSOCKET_REDIS_URL)
  47. USER_POOL = RedisDict("open-webui:user_pool", redis_url=WEBSOCKET_REDIS_URL)
  48. USAGE_POOL = RedisDict("open-webui:usage_pool", redis_url=WEBSOCKET_REDIS_URL)
  49. clean_up_lock = RedisLock(
  50. redis_url=WEBSOCKET_REDIS_URL,
  51. lock_name="usage_cleanup_lock",
  52. timeout_secs=TIMEOUT_DURATION * 2,
  53. )
  54. aquire_func = clean_up_lock.aquire_lock
  55. renew_func = clean_up_lock.renew_lock
  56. release_func = clean_up_lock.release_lock
  57. else:
  58. SESSION_POOL = {}
  59. USER_POOL = {}
  60. USAGE_POOL = {}
  61. aquire_func = release_func = renew_func = lambda: True
  62. async def periodic_usage_pool_cleanup():
  63. if not aquire_func():
  64. log.debug("Usage pool cleanup lock already exists. Not running it.")
  65. return
  66. log.debug("Running periodic_usage_pool_cleanup")
  67. try:
  68. while True:
  69. if not renew_func():
  70. log.error(f"Unable to renew cleanup lock. Exiting usage pool cleanup.")
  71. raise Exception("Unable to renew usage pool cleanup lock.")
  72. now = int(time.time())
  73. send_usage = False
  74. for model_id, connections in list(USAGE_POOL.items()):
  75. # Creating a list of sids to remove if they have timed out
  76. expired_sids = [
  77. sid
  78. for sid, details in connections.items()
  79. if now - details["updated_at"] > TIMEOUT_DURATION
  80. ]
  81. for sid in expired_sids:
  82. del connections[sid]
  83. if not connections:
  84. log.debug(f"Cleaning up model {model_id} from usage pool")
  85. del USAGE_POOL[model_id]
  86. else:
  87. USAGE_POOL[model_id] = connections
  88. send_usage = True
  89. if send_usage:
  90. # Emit updated usage information after cleaning
  91. await sio.emit("usage", {"models": get_models_in_use()})
  92. await asyncio.sleep(TIMEOUT_DURATION)
  93. finally:
  94. release_func()
  95. app = socketio.ASGIApp(
  96. sio,
  97. socketio_path="/ws/socket.io",
  98. )
  99. def get_models_in_use():
  100. # List models that are currently in use
  101. models_in_use = list(USAGE_POOL.keys())
  102. return models_in_use
  103. @sio.on("usage")
  104. async def usage(sid, data):
  105. model_id = data["model"]
  106. # Record the timestamp for the last update
  107. current_time = int(time.time())
  108. # Store the new usage data and task
  109. USAGE_POOL[model_id] = {
  110. **(USAGE_POOL[model_id] if model_id in USAGE_POOL else {}),
  111. sid: {"updated_at": current_time},
  112. }
  113. # Broadcast the usage data to all clients
  114. await sio.emit("usage", {"models": get_models_in_use()})
  115. @sio.event
  116. async def connect(sid, environ, auth):
  117. user = None
  118. if auth and "token" in auth:
  119. data = decode_token(auth["token"])
  120. if data is not None and "id" in data:
  121. user = Users.get_user_by_id(data["id"])
  122. if user:
  123. SESSION_POOL[sid] = user.model_dump()
  124. if user.id in USER_POOL:
  125. USER_POOL[user.id] = USER_POOL[user.id] + [sid]
  126. else:
  127. USER_POOL[user.id] = [sid]
  128. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  129. await sio.emit("user-list", {"user_ids": list(USER_POOL.keys())})
  130. await sio.emit("usage", {"models": get_models_in_use()})
  131. @sio.on("user-join")
  132. async def user_join(sid, data):
  133. auth = data["auth"] if "auth" in data else None
  134. if not auth or "token" not in auth:
  135. return
  136. data = decode_token(auth["token"])
  137. if data is None or "id" not in data:
  138. return
  139. user = Users.get_user_by_id(data["id"])
  140. if not user:
  141. return
  142. SESSION_POOL[sid] = user.model_dump()
  143. if user.id in USER_POOL:
  144. USER_POOL[user.id] = USER_POOL[user.id] + [sid]
  145. else:
  146. USER_POOL[user.id] = [sid]
  147. # Join all the channels
  148. channels = Channels.get_channels_by_user_id(user.id)
  149. log.debug(f"{channels=}")
  150. for channel in channels:
  151. await sio.enter_room(sid, f"channel:{channel.id}")
  152. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  153. await sio.emit("user-list", {"user_ids": list(USER_POOL.keys())})
  154. return {"id": user.id, "name": user.name}
  155. @sio.on("join-channels")
  156. async def join_channel(sid, data):
  157. auth = data["auth"] if "auth" in data else None
  158. if not auth or "token" not in auth:
  159. return
  160. data = decode_token(auth["token"])
  161. if data is None or "id" not in data:
  162. return
  163. user = Users.get_user_by_id(data["id"])
  164. if not user:
  165. return
  166. # Join all the channels
  167. channels = Channels.get_channels_by_user_id(user.id)
  168. log.debug(f"{channels=}")
  169. for channel in channels:
  170. await sio.enter_room(sid, f"channel:{channel.id}")
  171. @sio.on("channel-events")
  172. async def channel_events(sid, data):
  173. room = f"channel:{data['channel_id']}"
  174. participants = sio.manager.get_participants(
  175. namespace="/",
  176. room=room,
  177. )
  178. sids = [sid for sid, _ in participants]
  179. if sid not in sids:
  180. return
  181. event_data = data["data"]
  182. event_type = event_data["type"]
  183. if event_type == "typing":
  184. await sio.emit(
  185. "channel-events",
  186. {
  187. "channel_id": data["channel_id"],
  188. "data": event_data,
  189. "user": UserNameResponse(**SESSION_POOL[sid]).model_dump(),
  190. },
  191. room=room,
  192. )
  193. @sio.on("user-list")
  194. async def user_list(sid):
  195. await sio.emit("user-list", {"user_ids": list(USER_POOL.keys())})
  196. @sio.event
  197. async def disconnect(sid):
  198. if sid in SESSION_POOL:
  199. user = SESSION_POOL[sid]
  200. del SESSION_POOL[sid]
  201. user_id = user["id"]
  202. USER_POOL[user_id] = [_sid for _sid in USER_POOL[user_id] if _sid != sid]
  203. if len(USER_POOL[user_id]) == 0:
  204. del USER_POOL[user_id]
  205. await sio.emit("user-list", {"user_ids": list(USER_POOL.keys())})
  206. else:
  207. pass
  208. # print(f"Unknown session ID {sid} disconnected")
  209. def get_event_emitter(request_info):
  210. async def __event_emitter__(event_data):
  211. user_id = request_info["user_id"]
  212. session_ids = list(
  213. set(USER_POOL.get(user_id, []) + [request_info["session_id"]])
  214. )
  215. for session_id in session_ids:
  216. await sio.emit(
  217. "chat-events",
  218. {
  219. "chat_id": request_info["chat_id"],
  220. "message_id": request_info["message_id"],
  221. "data": event_data,
  222. },
  223. to=session_id,
  224. )
  225. if "type" in event_data and event_data["type"] == "status":
  226. Chats.add_message_status_to_chat_by_id_and_message_id(
  227. request_info["chat_id"],
  228. request_info["message_id"],
  229. event_data.get("data", {}),
  230. )
  231. return __event_emitter__
  232. def get_event_call(request_info):
  233. async def __event_call__(event_data):
  234. response = await sio.call(
  235. "chat-events",
  236. {
  237. "chat_id": request_info["chat_id"],
  238. "message_id": request_info["message_id"],
  239. "data": event_data,
  240. },
  241. to=request_info["session_id"],
  242. )
  243. return response
  244. return __event_call__
  245. def get_user_id_from_session_pool(sid):
  246. user = SESSION_POOL.get(sid)
  247. if user:
  248. return user["id"]
  249. return None
  250. def get_user_ids_from_room(room):
  251. active_session_ids = sio.manager.get_participants(
  252. namespace="/",
  253. room=room,
  254. )
  255. active_user_ids = list(
  256. set(
  257. [SESSION_POOL.get(session_id[0])["id"] for session_id in active_session_ids]
  258. )
  259. )
  260. return active_user_ids
  261. def get_active_status_by_user_id(user_id):
  262. if user_id in USER_POOL:
  263. return True
  264. return False