File size: 1,289 Bytes
066935a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
import asyncio
import json

app = FastAPI()

class ConnectionManager:
    def __init__(self):
        self.active_connections: list[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)

    async def broadcast(self, message: dict):
        for connection in self.active_connections:
            await connection.send_text(json.dumps(message))

manager = ConnectionManager()

@app.websocket("/ws/graph")
async def websocket_endpoint(websocket: WebSocket):
    await manager.connect(websocket)
    try:
        while True:
            # Mantém a conexão viva e aguarda triggers do kernel
            await websocket.receive_text() 
    except WebSocketDisconnect:
        manager.disconnect(websocket)

# Hook de Integração com o Ranking
async def trigger_ui_update(updated_data):
    """
    Envia o novo estado do grafo (nodos + ranking) para o React.
    """
    payload = {
        "type": "GRAPH_UPDATE",
        "payload": updated_data,
        "timestamp": "2026-03-17T23:10:07Z"
    }
    await manager.broadcast(payload)