main.py 12 KB

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