main.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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. user = Users.get_user_by_id(data["id"])
  20. if user:
  21. SESSION_POOL[sid] = user.id
  22. if user.id in USER_POOL:
  23. USER_POOL[user.id].append(sid)
  24. else:
  25. USER_POOL[user.id] = [sid]
  26. print(f"user {user.name}({user.id}) connected with session ID {sid}")
  27. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  28. await sio.emit("usage", {"models": get_models_in_use()})
  29. @sio.on("user-join")
  30. async def user_join(sid, data):
  31. print("user-join", sid, data)
  32. auth = data["auth"] if "auth" in data else None
  33. if auth and "token" in auth:
  34. data = decode_token(auth["token"])
  35. if data is not None and "id" in data:
  36. user = Users.get_user_by_id(data["id"])
  37. if user:
  38. SESSION_POOL[sid] = user.id
  39. if user.id in USER_POOL:
  40. USER_POOL[user.id].append(sid)
  41. else:
  42. USER_POOL[user.id] = [sid]
  43. print(f"user {user.name}({user.id}) connected with session ID {sid}")
  44. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  45. @sio.on("user-count")
  46. async def user_count(sid):
  47. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  48. def get_models_in_use():
  49. # Aggregate all models in use
  50. models_in_use = []
  51. for model_id, data in USAGE_POOL.items():
  52. models_in_use.append(model_id)
  53. return models_in_use
  54. @sio.on("usage")
  55. async def usage(sid, data):
  56. model_id = data["model"]
  57. # Cancel previous callback if there is one
  58. if model_id in USAGE_POOL:
  59. USAGE_POOL[model_id]["callback"].cancel()
  60. # Store the new usage data and task
  61. if model_id in USAGE_POOL:
  62. USAGE_POOL[model_id]["sids"].append(sid)
  63. USAGE_POOL[model_id]["sids"] = list(set(USAGE_POOL[model_id]["sids"]))
  64. else:
  65. USAGE_POOL[model_id] = {"sids": [sid]}
  66. # Schedule a task to remove the usage data after TIMEOUT_DURATION
  67. USAGE_POOL[model_id]["callback"] = asyncio.create_task(
  68. remove_after_timeout(sid, model_id)
  69. )
  70. # Broadcast the usage data to all clients
  71. await sio.emit("usage", {"models": get_models_in_use()})
  72. async def remove_after_timeout(sid, model_id):
  73. try:
  74. await asyncio.sleep(TIMEOUT_DURATION)
  75. if model_id in USAGE_POOL:
  76. print(USAGE_POOL[model_id]["sids"])
  77. USAGE_POOL[model_id]["sids"].remove(sid)
  78. USAGE_POOL[model_id]["sids"] = list(set(USAGE_POOL[model_id]["sids"]))
  79. if len(USAGE_POOL[model_id]["sids"]) == 0:
  80. del USAGE_POOL[model_id]
  81. # Broadcast the usage data to all clients
  82. await sio.emit("usage", {"models": get_models_in_use()})
  83. except asyncio.CancelledError:
  84. # Task was cancelled due to new 'usage' event
  85. pass
  86. @sio.event
  87. async def disconnect(sid):
  88. if sid in SESSION_POOL:
  89. user_id = SESSION_POOL[sid]
  90. del SESSION_POOL[sid]
  91. USER_POOL[user_id].remove(sid)
  92. if len(USER_POOL[user_id]) == 0:
  93. del USER_POOL[user_id]
  94. await sio.emit("user-count", {"count": len(USER_POOL)})
  95. else:
  96. print(f"Unknown session ID {sid} disconnected")