main.py 11 KB

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