main.py 11 KB

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