main.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. model_id = data["model"]
  137. # Record the timestamp for the last update
  138. current_time = int(time.time())
  139. # Store the new usage data and task
  140. USAGE_POOL[model_id] = {
  141. **(USAGE_POOL[model_id] if model_id in USAGE_POOL else {}),
  142. sid: {"updated_at": current_time},
  143. }
  144. # Broadcast the usage data to all clients
  145. await sio.emit("usage", {"models": get_models_in_use()})
  146. @sio.event
  147. async def connect(sid, environ, auth):
  148. user = None
  149. if auth and "token" in auth:
  150. data = decode_token(auth["token"])
  151. if data is not None and "id" in data:
  152. user = Users.get_user_by_id(data["id"])
  153. if user:
  154. SESSION_POOL[sid] = user.model_dump()
  155. if user.id in USER_POOL:
  156. USER_POOL[user.id] = USER_POOL[user.id] + [sid]
  157. else:
  158. USER_POOL[user.id] = [sid]
  159. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  160. await sio.emit("user-list", {"user_ids": list(USER_POOL.keys())})
  161. await sio.emit("usage", {"models": get_models_in_use()})
  162. @sio.on("user-join")
  163. async def user_join(sid, data):
  164. auth = data["auth"] if "auth" in data else None
  165. if not auth or "token" not in auth:
  166. return
  167. data = decode_token(auth["token"])
  168. if data is None or "id" not in data:
  169. return
  170. user = Users.get_user_by_id(data["id"])
  171. if not user:
  172. return
  173. SESSION_POOL[sid] = user.model_dump()
  174. if user.id in USER_POOL:
  175. USER_POOL[user.id] = USER_POOL[user.id] + [sid]
  176. else:
  177. USER_POOL[user.id] = [sid]
  178. # Join all the channels
  179. channels = Channels.get_channels_by_user_id(user.id)
  180. log.debug(f"{channels=}")
  181. for channel in channels:
  182. await sio.enter_room(sid, f"channel:{channel.id}")
  183. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  184. await sio.emit("user-list", {"user_ids": list(USER_POOL.keys())})
  185. return {"id": user.id, "name": user.name}
  186. @sio.on("join-channels")
  187. async def join_channel(sid, data):
  188. auth = data["auth"] if "auth" in data else None
  189. if not auth or "token" not in auth:
  190. return
  191. data = decode_token(auth["token"])
  192. if data is None or "id" not in data:
  193. return
  194. user = Users.get_user_by_id(data["id"])
  195. if not user:
  196. return
  197. # Join all the channels
  198. channels = Channels.get_channels_by_user_id(user.id)
  199. log.debug(f"{channels=}")
  200. for channel in channels:
  201. await sio.enter_room(sid, f"channel:{channel.id}")
  202. @sio.on("channel-events")
  203. async def channel_events(sid, data):
  204. room = f"channel:{data['channel_id']}"
  205. participants = sio.manager.get_participants(
  206. namespace="/",
  207. room=room,
  208. )
  209. sids = [sid for sid, _ in participants]
  210. if sid not in sids:
  211. return
  212. event_data = data["data"]
  213. event_type = event_data["type"]
  214. if event_type == "typing":
  215. await sio.emit(
  216. "channel-events",
  217. {
  218. "channel_id": data["channel_id"],
  219. "message_id": data.get("message_id", None),
  220. "data": event_data,
  221. "user": UserNameResponse(**SESSION_POOL[sid]).model_dump(),
  222. },
  223. room=room,
  224. )
  225. @sio.on("user-list")
  226. async def user_list(sid):
  227. await sio.emit("user-list", {"user_ids": list(USER_POOL.keys())})
  228. @sio.event
  229. async def disconnect(sid):
  230. if sid in SESSION_POOL:
  231. user = SESSION_POOL[sid]
  232. del SESSION_POOL[sid]
  233. user_id = user["id"]
  234. USER_POOL[user_id] = [_sid for _sid in USER_POOL[user_id] if _sid != sid]
  235. if len(USER_POOL[user_id]) == 0:
  236. del USER_POOL[user_id]
  237. await sio.emit("user-list", {"user_ids": list(USER_POOL.keys())})
  238. else:
  239. pass
  240. # print(f"Unknown session ID {sid} disconnected")
  241. def get_event_emitter(request_info, update_db=True):
  242. async def __event_emitter__(event_data):
  243. user_id = request_info["user_id"]
  244. session_ids = list(
  245. set(
  246. USER_POOL.get(user_id, [])
  247. + (
  248. [request_info.get("session_id")]
  249. if request_info.get("session_id")
  250. else []
  251. )
  252. )
  253. )
  254. for session_id in session_ids:
  255. await sio.emit(
  256. "chat-events",
  257. {
  258. "chat_id": request_info.get("chat_id", None),
  259. "message_id": request_info.get("message_id", None),
  260. "data": event_data,
  261. },
  262. to=session_id,
  263. )
  264. if update_db:
  265. if "type" in event_data and event_data["type"] == "status":
  266. Chats.add_message_status_to_chat_by_id_and_message_id(
  267. request_info["chat_id"],
  268. request_info["message_id"],
  269. event_data.get("data", {}),
  270. )
  271. if "type" in event_data and event_data["type"] == "message":
  272. message = Chats.get_message_by_id_and_message_id(
  273. request_info["chat_id"],
  274. request_info["message_id"],
  275. )
  276. if message:
  277. content = message.get("content", "")
  278. content += event_data.get("data", {}).get("content", "")
  279. Chats.upsert_message_to_chat_by_id_and_message_id(
  280. request_info["chat_id"],
  281. request_info["message_id"],
  282. {
  283. "content": content,
  284. },
  285. )
  286. if "type" in event_data and event_data["type"] == "replace":
  287. content = event_data.get("data", {}).get("content", "")
  288. Chats.upsert_message_to_chat_by_id_and_message_id(
  289. request_info["chat_id"],
  290. request_info["message_id"],
  291. {
  292. "content": content,
  293. },
  294. )
  295. return __event_emitter__
  296. def get_event_call(request_info):
  297. async def __event_caller__(event_data):
  298. response = await sio.call(
  299. "chat-events",
  300. {
  301. "chat_id": request_info.get("chat_id", None),
  302. "message_id": request_info.get("message_id", None),
  303. "data": event_data,
  304. },
  305. to=request_info["session_id"],
  306. )
  307. return response
  308. return __event_caller__
  309. get_event_caller = get_event_call
  310. def get_user_id_from_session_pool(sid):
  311. user = SESSION_POOL.get(sid)
  312. if user:
  313. return user["id"]
  314. return None
  315. def get_user_ids_from_room(room):
  316. active_session_ids = sio.manager.get_participants(
  317. namespace="/",
  318. room=room,
  319. )
  320. active_user_ids = list(
  321. set(
  322. [SESSION_POOL.get(session_id[0])["id"] for session_id in active_session_ids]
  323. )
  324. )
  325. return active_user_ids
  326. def get_active_status_by_user_id(user_id):
  327. if user_id in USER_POOL:
  328. return True
  329. return False