main.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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. @sio.on("user-join")
  26. async def user_join(sid, data):
  27. print("user-join", sid, data)
  28. auth = data["auth"] if "auth" in data else None
  29. if auth and "token" in auth:
  30. data = decode_token(auth["token"])
  31. if data is not None and "id" in data:
  32. user = Users.get_user_by_id(data["id"])
  33. if user:
  34. USER_POOL[sid] = user.id
  35. print(f"user {user.name}({user.id}) connected with session ID {sid}")
  36. print(len(set(USER_POOL)))
  37. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  38. @sio.on("user-count")
  39. async def user_count(sid):
  40. print("user-count", sid)
  41. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  42. def get_models_in_use():
  43. # Aggregate all models in use
  44. models_in_use = []
  45. for sid, data in USAGE_POOL.items():
  46. models_in_use.extend(data["models"])
  47. print(f"Models in use: {models_in_use}")
  48. return models_in_use
  49. @sio.on("usage")
  50. async def usage(sid, data):
  51. print(f'Received "usage" event from {sid}: {data}')
  52. # Cancel previous task if there is one
  53. if sid in USAGE_POOL:
  54. USAGE_POOL[sid]["task"].cancel()
  55. # Store the new usage data and task
  56. model_id = data["model"]
  57. if sid in USAGE_POOL and "models" in USAGE_POOL[sid]:
  58. print(USAGE_POOL[sid])
  59. models = USAGE_POOL[sid]["models"]
  60. if model_id not in models:
  61. models.append(model_id)
  62. USAGE_POOL[sid] = {"models": models}
  63. else:
  64. USAGE_POOL[sid] = {"models": [model_id]}
  65. # Schedule a task to remove the usage data after TIMEOUT_DURATION
  66. USAGE_POOL[sid]["task"] = asyncio.create_task(remove_after_timeout(sid, model_id))
  67. models_in_use = get_models_in_use()
  68. # Broadcast the usage data to all clients
  69. await sio.emit("usage", {"models": models_in_use})
  70. async def remove_after_timeout(sid, model_id):
  71. try:
  72. await asyncio.sleep(TIMEOUT_DURATION)
  73. if sid in USAGE_POOL:
  74. if model_id in USAGE_POOL[sid]["models"]:
  75. USAGE_POOL[sid]["models"].remove(model_id)
  76. if len(USAGE_POOL[sid]["models"]) == 0:
  77. del USAGE_POOL[sid]
  78. print(f"Removed usage data for {sid} due to timeout")
  79. models_in_use = get_models_in_use()
  80. # Broadcast the usage data to all clients
  81. await sio.emit("usage", {"models": 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")