main.py 11 KB

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