main.py 4.2 KB

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