main.py 12 KB

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