main.py 5.9 KB

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