main.py 3.72 KB
Newer Older
Timothy J. Baek's avatar
Timothy J. Baek committed
1
import socketio
2
3
import asyncio

Timothy J. Baek's avatar
Timothy J. Baek committed
4
5
6
7
8
9
10
11

from apps.webui.models.users import Users
from utils.utils import decode_token

sio = socketio.AsyncServer(cors_allowed_origins=[], async_mode="asgi")
app = socketio.ASGIApp(sio, socketio_path="/ws/socket.io")

# Dictionary to maintain the user pool
Timothy J. Baek's avatar
Timothy J. Baek committed
12
13


Timothy J. Baek's avatar
Timothy J. Baek committed
14
USER_POOL = {}
15
16
17
USAGE_POOL = {}
# Timeout duration in seconds
TIMEOUT_DURATION = 3
Timothy J. Baek's avatar
Timothy J. Baek committed
18
19
20
21
22
23
24


@sio.event
async def connect(sid, environ, auth):
    print("connect ", sid)

    user = None
Timothy J. Baek's avatar
Timothy J. Baek committed
25
26
27
28
29
30
31
    if auth and "token" in auth:
        data = decode_token(auth["token"])

        if data is not None and "id" in data:
            user = Users.get_user_by_id(data["id"])

        if user:
Timothy J. Baek's avatar
Timothy J. Baek committed
32
            USER_POOL[sid] = user.id
Timothy J. Baek's avatar
Timothy J. Baek committed
33
            print(f"user {user.name}({user.id}) connected with session ID {sid}")
Timothy J. Baek's avatar
Timothy J. Baek committed
34

Timothy J. Baek's avatar
Timothy J. Baek committed
35
36
            print(len(set(USER_POOL)))
            await sio.emit("user-count", {"count": len(set(USER_POOL))})
Timothy J. Baek's avatar
Timothy J. Baek committed
37
            await sio.emit("usage", {"models": get_models_in_use()})
Timothy J. Baek's avatar
Timothy J. Baek committed
38
39


Timothy J. Baek's avatar
Timothy J. Baek committed
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
@sio.on("user-join")
async def user_join(sid, data):
    print("user-join", sid, data)

    auth = data["auth"] if "auth" in data else None

    if auth and "token" in auth:
        data = decode_token(auth["token"])

        if data is not None and "id" in data:
            user = Users.get_user_by_id(data["id"])

        if user:
            USER_POOL[sid] = user.id
            print(f"user {user.name}({user.id}) connected with session ID {sid}")

            print(len(set(USER_POOL)))
            await sio.emit("user-count", {"count": len(set(USER_POOL))})


Timothy J. Baek's avatar
Timothy J. Baek committed
60
61
62
63
64
@sio.on("user-count")
async def user_count(sid):
    print("user-count", sid)
    await sio.emit("user-count", {"count": len(set(USER_POOL))})

Timothy J. Baek's avatar
Timothy J. Baek committed
65

66
67
68
def get_models_in_use():
    # Aggregate all models in use
    models_in_use = []
Timothy J. Baek's avatar
Timothy J. Baek committed
69
70
    for model_id, data in USAGE_POOL.items():
        models_in_use.append(model_id)
71
72
73
74
75
76
77
78
79
80
81
    print(f"Models in use: {models_in_use}")

    return models_in_use


@sio.on("usage")
async def usage(sid, data):
    print(f'Received "usage" event from {sid}: {data}')

    model_id = data["model"]

Timothy J. Baek's avatar
Timothy J. Baek committed
82
83
84
    # Cancel previous callback if there is one
    if model_id in USAGE_POOL:
        USAGE_POOL[model_id]["callback"].cancel()
85

Timothy J. Baek's avatar
Timothy J. Baek committed
86
    # Store the new usage data and task
87

Timothy J. Baek's avatar
Timothy J. Baek committed
88
89
90
    if model_id in USAGE_POOL:
        USAGE_POOL[model_id]["sids"].append(sid)
        USAGE_POOL[model_id]["sids"] = list(set(USAGE_POOL[model_id]["sids"]))
91
92

    else:
Timothy J. Baek's avatar
Timothy J. Baek committed
93
        USAGE_POOL[model_id] = {"sids": [sid]}
94
95

    # Schedule a task to remove the usage data after TIMEOUT_DURATION
Timothy J. Baek's avatar
Timothy J. Baek committed
96
97
98
    USAGE_POOL[model_id]["callback"] = asyncio.create_task(
        remove_after_timeout(sid, model_id)
    )
99
100

    # Broadcast the usage data to all clients
Timothy J. Baek's avatar
Timothy J. Baek committed
101
    await sio.emit("usage", {"models": get_models_in_use()})
102
103
104
105


async def remove_after_timeout(sid, model_id):
    try:
Timothy J. Baek's avatar
Timothy J. Baek committed
106
        print("remove_after_timeout", sid, model_id)
107
        await asyncio.sleep(TIMEOUT_DURATION)
Timothy J. Baek's avatar
Timothy J. Baek committed
108
109
110
111
112
113
114
115
116
        if model_id in USAGE_POOL:
            print(USAGE_POOL[model_id]["sids"])
            USAGE_POOL[model_id]["sids"].remove(sid)
            USAGE_POOL[model_id]["sids"] = list(set(USAGE_POOL[model_id]["sids"]))

            if len(USAGE_POOL[model_id]["sids"]) == 0:
                del USAGE_POOL[model_id]

            print(f"Removed usage data for {model_id} due to timeout")
117
            # Broadcast the usage data to all clients
Timothy J. Baek's avatar
Timothy J. Baek committed
118
            await sio.emit("usage", {"models": get_models_in_use()})
119
120
121
122
123
    except asyncio.CancelledError:
        # Task was cancelled due to new 'usage' event
        pass


Timothy J. Baek's avatar
Timothy J. Baek committed
124
@sio.event
Timothy J. Baek's avatar
Timothy J. Baek committed
125
async def disconnect(sid):
Timothy J. Baek's avatar
Timothy J. Baek committed
126
127
128
    if sid in USER_POOL:
        disconnected_user = USER_POOL.pop(sid)
        print(f"user {disconnected_user} disconnected with session ID {sid}")
Timothy J. Baek's avatar
Timothy J. Baek committed
129
130

        await sio.emit("user-count", {"count": len(USER_POOL)})
Timothy J. Baek's avatar
Timothy J. Baek committed
131
132
    else:
        print(f"Unknown session ID {sid} disconnected")