main.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. import asyncio
  2. import socketio
  3. import logging
  4. import sys
  5. import time
  6. from open_webui.apps.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.utils import decode_token
  13. from open_webui.apps.socket.utils import RedisDict
  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=(
  27. ["polling", "websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]
  28. ),
  29. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  30. always_connect=True,
  31. client_manager=mgr,
  32. )
  33. else:
  34. sio = socketio.AsyncServer(
  35. cors_allowed_origins=[],
  36. async_mode="asgi",
  37. transports=(
  38. ["polling", "websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]
  39. ),
  40. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  41. always_connect=True,
  42. )
  43. # Dictionary to maintain the user pool
  44. if WEBSOCKET_MANAGER == "redis":
  45. SESSION_POOL = RedisDict("open-webui:session_pool", redis_url=WEBSOCKET_REDIS_URL)
  46. USER_POOL = RedisDict("open-webui:user_pool", redis_url=WEBSOCKET_REDIS_URL)
  47. USAGE_POOL = RedisDict("open-webui:usage_pool", redis_url=WEBSOCKET_REDIS_URL)
  48. else:
  49. SESSION_POOL = {}
  50. USER_POOL = {}
  51. USAGE_POOL = {}
  52. # Timeout duration in seconds
  53. TIMEOUT_DURATION = 3
  54. async def periodic_usage_pool_cleanup():
  55. while True:
  56. now = int(time.time())
  57. for model_id, connections in list(USAGE_POOL.items()):
  58. # Creating a list of sids to remove if they have timed out
  59. expired_sids = [
  60. sid
  61. for sid, details in connections.items()
  62. if now - details["updated_at"] > TIMEOUT_DURATION
  63. ]
  64. for sid in expired_sids:
  65. del connections[sid]
  66. if not connections:
  67. log.debug(f"Cleaning up model {model_id} from usage pool")
  68. del USAGE_POOL[model_id]
  69. else:
  70. USAGE_POOL[model_id] = connections
  71. # Emit updated usage information after cleaning
  72. await sio.emit("usage", {"models": get_models_in_use()})
  73. await asyncio.sleep(TIMEOUT_DURATION)
  74. app = socketio.ASGIApp(
  75. sio,
  76. socketio_path="/ws/socket.io",
  77. on_startup=asyncio.create_task(periodic_usage_pool_cleanup()),
  78. )
  79. def get_models_in_use():
  80. # List models that are currently in use
  81. models_in_use = list(USAGE_POOL.keys())
  82. return models_in_use
  83. @sio.on("usage")
  84. async def usage(sid, data):
  85. model_id = data["model"]
  86. # Record the timestamp for the last update
  87. current_time = int(time.time())
  88. # Store the new usage data and task
  89. USAGE_POOL[model_id] = {
  90. **(USAGE_POOL[model_id] if model_id in USAGE_POOL else {}),
  91. sid: {"updated_at": current_time},
  92. }
  93. # Broadcast the usage data to all clients
  94. await sio.emit("usage", {"models": get_models_in_use()})
  95. @sio.event
  96. async def connect(sid, environ, auth):
  97. user = None
  98. if auth and "token" in auth:
  99. data = decode_token(auth["token"])
  100. if data is not None and "id" in data:
  101. user = Users.get_user_by_id(data["id"])
  102. if user:
  103. SESSION_POOL[sid] = user.id
  104. if user.id in USER_POOL:
  105. USER_POOL[user.id].append(sid)
  106. else:
  107. USER_POOL[user.id] = [sid]
  108. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  109. await sio.emit("user-count", {"count": len(USER_POOL.items())})
  110. await sio.emit("usage", {"models": get_models_in_use()})
  111. @sio.on("user-join")
  112. async def user_join(sid, data):
  113. # print("user-join", sid, data)
  114. auth = data["auth"] if "auth" in data else None
  115. if not auth or "token" not in auth:
  116. return
  117. data = decode_token(auth["token"])
  118. if data is None or "id" not in data:
  119. return
  120. user = Users.get_user_by_id(data["id"])
  121. if not user:
  122. return
  123. SESSION_POOL[sid] = user.id
  124. if user.id in USER_POOL:
  125. USER_POOL[user.id].append(sid)
  126. else:
  127. USER_POOL[user.id] = [sid]
  128. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  129. await sio.emit("user-count", {"count": len(USER_POOL.items())})
  130. @sio.on("user-count")
  131. async def user_count(sid):
  132. await sio.emit("user-count", {"count": len(USER_POOL.items())})
  133. @sio.event
  134. async def disconnect(sid):
  135. if sid in SESSION_POOL:
  136. user_id = SESSION_POOL[sid]
  137. del SESSION_POOL[sid]
  138. USER_POOL[user_id] = [_sid for _sid in USER_POOL[user_id] if _sid != sid]
  139. if len(USER_POOL[user_id]) == 0:
  140. del USER_POOL[user_id]
  141. await sio.emit("user-count", {"count": len(USER_POOL)})
  142. else:
  143. pass
  144. # print(f"Unknown session ID {sid} disconnected")
  145. def get_event_emitter(request_info):
  146. async def __event_emitter__(event_data):
  147. await sio.emit(
  148. "chat-events",
  149. {
  150. "chat_id": request_info["chat_id"],
  151. "message_id": request_info["message_id"],
  152. "data": event_data,
  153. },
  154. to=request_info["session_id"],
  155. )
  156. return __event_emitter__
  157. def get_event_call(request_info):
  158. async def __event_call__(event_data):
  159. response = await sio.call(
  160. "chat-events",
  161. {
  162. "chat_id": request_info["chat_id"],
  163. "message_id": request_info["message_id"],
  164. "data": event_data,
  165. },
  166. to=request_info["session_id"],
  167. )
  168. return response
  169. return __event_call__