1
0

main.py 3.7 KB

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