main.py 11 KB

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