main.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. import socketio
  2. import asyncio
  3. from apps.webui.models.users import Users
  4. from utils.utils import decode_token
  5. sio = socketio.AsyncServer(cors_allowed_origins=[], async_mode="asgi")
  6. app = socketio.ASGIApp(sio, socketio_path="/ws/socket.io")
  7. # Dictionary to maintain the user pool
  8. SESSION_POOL = {}
  9. USER_POOL = {}
  10. USAGE_POOL = {}
  11. # Timeout duration in seconds
  12. TIMEOUT_DURATION = 3
  13. @sio.event
  14. async def connect(sid, environ, auth):
  15. user = None
  16. if auth and "token" in auth:
  17. data = decode_token(auth["token"])
  18. if data is not None and "id" in data:
  19. from apps.webui.internal.db import SessionLocal
  20. user = Users.get_user_by_id(SessionLocal(), data["id"])
  21. if user:
  22. SESSION_POOL[sid] = user.id
  23. if user.id in USER_POOL:
  24. USER_POOL[user.id].append(sid)
  25. else:
  26. USER_POOL[user.id] = [sid]
  27. print(f"user {user.name}({user.id}) connected with session ID {sid}")
  28. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  29. await sio.emit("usage", {"models": get_models_in_use()})
  30. @sio.on("user-join")
  31. async def user_join(sid, data):
  32. print("user-join", sid, data)
  33. auth = data["auth"] if "auth" in data else None
  34. if auth and "token" in auth:
  35. data = decode_token(auth["token"])
  36. if data is not None and "id" in data:
  37. user = Users.get_user_by_id(data["id"])
  38. if user:
  39. SESSION_POOL[sid] = user.id
  40. if user.id in USER_POOL:
  41. USER_POOL[user.id].append(sid)
  42. else:
  43. USER_POOL[user.id] = [sid]
  44. print(f"user {user.name}({user.id}) connected with session ID {sid}")
  45. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  46. @sio.on("user-count")
  47. async def user_count(sid):
  48. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  49. def get_models_in_use():
  50. # Aggregate all models in use
  51. models_in_use = []
  52. for model_id, data in USAGE_POOL.items():
  53. models_in_use.append(model_id)
  54. return models_in_use
  55. @sio.on("usage")
  56. async def usage(sid, data):
  57. model_id = data["model"]
  58. # Cancel previous callback if there is one
  59. if model_id in USAGE_POOL:
  60. USAGE_POOL[model_id]["callback"].cancel()
  61. # Store the new usage data and task
  62. if model_id in USAGE_POOL:
  63. USAGE_POOL[model_id]["sids"].append(sid)
  64. USAGE_POOL[model_id]["sids"] = list(set(USAGE_POOL[model_id]["sids"]))
  65. else:
  66. USAGE_POOL[model_id] = {"sids": [sid]}
  67. # Schedule a task to remove the usage data after TIMEOUT_DURATION
  68. USAGE_POOL[model_id]["callback"] = asyncio.create_task(
  69. remove_after_timeout(sid, model_id)
  70. )
  71. # Broadcast the usage data to all clients
  72. await sio.emit("usage", {"models": get_models_in_use()})
  73. async def remove_after_timeout(sid, model_id):
  74. try:
  75. await asyncio.sleep(TIMEOUT_DURATION)
  76. if model_id in USAGE_POOL:
  77. print(USAGE_POOL[model_id]["sids"])
  78. USAGE_POOL[model_id]["sids"].remove(sid)
  79. USAGE_POOL[model_id]["sids"] = list(set(USAGE_POOL[model_id]["sids"]))
  80. if len(USAGE_POOL[model_id]["sids"]) == 0:
  81. del USAGE_POOL[model_id]
  82. # Broadcast the usage data to all clients
  83. await sio.emit("usage", {"models": get_models_in_use()})
  84. except asyncio.CancelledError:
  85. # Task was cancelled due to new 'usage' event
  86. pass
  87. @sio.event
  88. async def disconnect(sid):
  89. if sid in SESSION_POOL:
  90. user_id = SESSION_POOL[sid]
  91. del SESSION_POOL[sid]
  92. USER_POOL[user_id].remove(sid)
  93. if len(USER_POOL[user_id]) == 0:
  94. del USER_POOL[user_id]
  95. await sio.emit("user-count", {"count": len(USER_POOL)})
  96. else:
  97. print(f"Unknown session ID {sid} disconnected")