main.py 10 KB

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