main.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import asyncio
  2. import socketio
  3. import logging
  4. import sys
  5. import time
  6. from open_webui.models.users import Users
  7. from open_webui.env import (
  8. ENABLE_WEBSOCKET_SUPPORT,
  9. WEBSOCKET_MANAGER,
  10. WEBSOCKET_REDIS_URL,
  11. )
  12. from open_webui.utils.auth import decode_token
  13. from open_webui.socket.utils import RedisDict, RedisLock
  14. from open_webui.env import (
  15. GLOBAL_LOG_LEVEL,
  16. SRC_LOG_LEVELS,
  17. )
  18. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  19. log = logging.getLogger(__name__)
  20. log.setLevel(SRC_LOG_LEVELS["SOCKET"])
  21. if WEBSOCKET_MANAGER == "redis":
  22. mgr = socketio.AsyncRedisManager(WEBSOCKET_REDIS_URL)
  23. sio = socketio.AsyncServer(
  24. cors_allowed_origins=[],
  25. async_mode="asgi",
  26. transports=(["websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]),
  27. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  28. always_connect=True,
  29. client_manager=mgr,
  30. )
  31. else:
  32. sio = socketio.AsyncServer(
  33. cors_allowed_origins=[],
  34. async_mode="asgi",
  35. transports=(["websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]),
  36. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  37. always_connect=True,
  38. )
  39. # Timeout duration in seconds
  40. TIMEOUT_DURATION = 3
  41. # Dictionary to maintain the user pool
  42. if WEBSOCKET_MANAGER == "redis":
  43. log.debug("Using Redis to manage websockets.")
  44. SESSION_POOL = RedisDict("open-webui:session_pool", redis_url=WEBSOCKET_REDIS_URL)
  45. USER_POOL = RedisDict("open-webui:user_pool", redis_url=WEBSOCKET_REDIS_URL)
  46. USAGE_POOL = RedisDict("open-webui:usage_pool", redis_url=WEBSOCKET_REDIS_URL)
  47. clean_up_lock = RedisLock(
  48. redis_url=WEBSOCKET_REDIS_URL,
  49. lock_name="usage_cleanup_lock",
  50. timeout_secs=TIMEOUT_DURATION * 2,
  51. )
  52. aquire_func = clean_up_lock.aquire_lock
  53. renew_func = clean_up_lock.renew_lock
  54. release_func = clean_up_lock.release_lock
  55. else:
  56. SESSION_POOL = {}
  57. USER_POOL = {}
  58. USAGE_POOL = {}
  59. aquire_func = release_func = renew_func = lambda: True
  60. async def periodic_usage_pool_cleanup():
  61. if not aquire_func():
  62. log.debug("Usage pool cleanup lock already exists. Not running it.")
  63. return
  64. log.debug("Running periodic_usage_pool_cleanup")
  65. try:
  66. while True:
  67. if not renew_func():
  68. log.error(f"Unable to renew cleanup lock. Exiting usage pool cleanup.")
  69. raise Exception("Unable to renew usage pool cleanup lock.")
  70. now = int(time.time())
  71. send_usage = False
  72. for model_id, connections in list(USAGE_POOL.items()):
  73. # Creating a list of sids to remove if they have timed out
  74. expired_sids = [
  75. sid
  76. for sid, details in connections.items()
  77. if now - details["updated_at"] > TIMEOUT_DURATION
  78. ]
  79. for sid in expired_sids:
  80. del connections[sid]
  81. if not connections:
  82. log.debug(f"Cleaning up model {model_id} from usage pool")
  83. del USAGE_POOL[model_id]
  84. else:
  85. USAGE_POOL[model_id] = connections
  86. send_usage = True
  87. if send_usage:
  88. # Emit updated usage information after cleaning
  89. await sio.emit("usage", {"models": get_models_in_use()})
  90. await asyncio.sleep(TIMEOUT_DURATION)
  91. finally:
  92. release_func()
  93. app = socketio.ASGIApp(
  94. sio,
  95. socketio_path="/ws/socket.io",
  96. )
  97. def get_models_in_use():
  98. # List models that are currently in use
  99. models_in_use = list(USAGE_POOL.keys())
  100. return models_in_use
  101. @sio.on("usage")
  102. async def usage(sid, data):
  103. model_id = data["model"]
  104. # Record the timestamp for the last update
  105. current_time = int(time.time())
  106. # Store the new usage data and task
  107. USAGE_POOL[model_id] = {
  108. **(USAGE_POOL[model_id] if model_id in USAGE_POOL else {}),
  109. sid: {"updated_at": current_time},
  110. }
  111. # Broadcast the usage data to all clients
  112. await sio.emit("usage", {"models": get_models_in_use()})
  113. @sio.event
  114. async def connect(sid, environ, auth):
  115. user = None
  116. if auth and "token" in auth:
  117. data = decode_token(auth["token"])
  118. if data is not None and "id" in data:
  119. user = Users.get_user_by_id(data["id"])
  120. if user:
  121. SESSION_POOL[sid] = user.id
  122. if user.id in USER_POOL:
  123. USER_POOL[user.id].append(sid)
  124. else:
  125. USER_POOL[user.id] = [sid]
  126. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  127. await sio.emit("user-count", {"count": len(USER_POOL.items())})
  128. await sio.emit("usage", {"models": get_models_in_use()})
  129. @sio.on("user-join")
  130. async def user_join(sid, data):
  131. # print("user-join", sid, data)
  132. auth = data["auth"] if "auth" in data else None
  133. if not auth or "token" not in auth:
  134. return
  135. data = decode_token(auth["token"])
  136. if data is None or "id" not in data:
  137. return
  138. user = Users.get_user_by_id(data["id"])
  139. if not user:
  140. return
  141. SESSION_POOL[sid] = user.id
  142. if user.id in USER_POOL:
  143. USER_POOL[user.id].append(sid)
  144. else:
  145. USER_POOL[user.id] = [sid]
  146. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  147. await sio.emit("user-count", {"count": len(USER_POOL.items())})
  148. @sio.on("user-count")
  149. async def user_count(sid):
  150. await sio.emit("user-count", {"count": len(USER_POOL.items())})
  151. @sio.on("chat")
  152. async def chat(sid, data):
  153. print("chat", sid, SESSION_POOL[sid], data)
  154. @sio.event
  155. async def disconnect(sid):
  156. if sid in SESSION_POOL:
  157. user_id = SESSION_POOL[sid]
  158. del SESSION_POOL[sid]
  159. USER_POOL[user_id] = [_sid for _sid in USER_POOL[user_id] if _sid != sid]
  160. if len(USER_POOL[user_id]) == 0:
  161. del USER_POOL[user_id]
  162. await sio.emit("user-count", {"count": len(USER_POOL)})
  163. else:
  164. pass
  165. # print(f"Unknown session ID {sid} disconnected")
  166. def get_event_emitter(request_info):
  167. async def __event_emitter__(event_data):
  168. user_id = request_info["user_id"]
  169. session_ids = list(
  170. set(USER_POOL.get(user_id, []) + [request_info["session_id"]])
  171. )
  172. for session_id in session_ids:
  173. await sio.emit(
  174. "chat-events",
  175. {
  176. "chat_id": request_info["chat_id"],
  177. "message_id": request_info["message_id"],
  178. "data": event_data,
  179. },
  180. to=session_id,
  181. )
  182. return __event_emitter__
  183. def get_event_call(request_info):
  184. async def __event_call__(event_data):
  185. response = await sio.call(
  186. "chat-events",
  187. {
  188. "chat_id": request_info["chat_id"],
  189. "message_id": request_info["message_id"],
  190. "data": event_data,
  191. },
  192. to=request_info["session_id"],
  193. )
  194. return response
  195. return __event_call__