patharanor commited on
Commit
4096277
·
1 Parent(s): 70fc246

improve websocket connection

Browse files
app.py CHANGED
@@ -1,17 +1,37 @@
1
- from fastapi import FastAPI, Response, WebSocket, WebSocketDisconnect, Depends, HTTPException
2
- from fastapi.middleware.cors import CORSMiddleware
 
3
  import uvicorn
4
- from dotenv import load_dotenv
5
  import os
 
 
 
 
 
 
 
 
6
 
7
  # Load environment variables from .env file
8
  load_dotenv()
9
  IS_DEV = os.environ.get('ENV', 'DEV') != 'PROD'
10
- SECURE_TOKEN = os.getenv("SECURE_TOKEN")
 
11
  X_REQUEST_USER = os.environ.get('X_REQUEST_USER')
12
  X_API_KEY = os.environ.get('X_API_KEY')
13
 
 
 
14
  app = FastAPI()
 
 
 
 
 
 
 
 
 
15
 
16
  # CORS Middleware: restrict access to only trusted origins
17
  app.add_middleware(
@@ -23,31 +43,68 @@ app.add_middleware(
23
  allow_headers=["*"],
24
  )
25
 
26
-
27
- # Simple token-based authentication dependency
28
- async def authenticate_token(token: str):
29
- if token != f"Bearer {SECURE_TOKEN}":
30
- raise HTTPException(status_code=401, detail="Invalid token")
31
-
32
  @app.get("/")
33
  def root():
34
- return Response(status=200, data='ok')
35
 
36
  @app.get("/health")
37
  def healthcheck():
38
- return Response(status=200, data='ok')
 
 
 
 
 
 
 
 
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  # WebSocket endpoint
41
  @app.websocket("/ws")
42
- async def websocket_endpoint(websocket: WebSocket, token: str = Depends(authenticate_token)):
43
- await websocket.accept()
 
 
 
 
 
 
 
 
 
 
44
  try:
45
  while True:
46
- data = await websocket.receive_text()
47
- print(f"Message from client: {data}")
48
- await websocket.send_text(f"Server received: {data}")
 
 
 
 
 
 
49
  except WebSocketDisconnect:
50
- print("Client disconnected")
 
 
 
51
 
52
  def is_valid(u, p):
53
  return u == X_REQUEST_USER and p == X_API_KEY
 
1
+ import asyncio
2
+ import logging
3
+ from fastapi.concurrency import asynccontextmanager
4
  import uvicorn
 
5
  import os
6
+ from dotenv import load_dotenv
7
+ from fastapi import FastAPI, Response, WebSocket, WebSocketDisconnect, status, HTTPException
8
+ from fastapi.middleware.cors import CORSMiddleware
9
+ from fastapi.responses import JSONResponse
10
+
11
+ from models.connection_manager import ConnectionManager
12
+ from models.request_payload import RequestPayload
13
+ from utils.package_manager import PackageManager
14
 
15
  # Load environment variables from .env file
16
  load_dotenv()
17
  IS_DEV = os.environ.get('ENV', 'DEV') != 'PROD'
18
+ WEBSOCKET_SECURE_TOKEN = os.getenv("SECURE_TOKEN")
19
+ WHITELIST_CHANNEL_IDS = os.getenv('WHITELIST_CHANNEL_IDS')
20
  X_REQUEST_USER = os.environ.get('X_REQUEST_USER')
21
  X_API_KEY = os.environ.get('X_API_KEY')
22
 
23
+ WHITELIST_CHANNEL_IDS = WHITELIST_CHANNEL_IDS.split(',') if WHITELIST_CHANNEL_IDS is not None else []
24
+
25
  app = FastAPI()
26
+ # Initialize the connection manager
27
+ manager = ConnectionManager()
28
+ package = PackageManager()
29
+
30
+ logging.basicConfig(
31
+ level=logging.WARNING,
32
+ format='%(asctime)s %(name)s %(levelname)-8s %(message)s',
33
+ datefmt='(%H:%M:%S)'
34
+ )
35
 
36
  # CORS Middleware: restrict access to only trusted origins
37
  app.add_middleware(
 
43
  allow_headers=["*"],
44
  )
45
 
 
 
 
 
 
 
46
  @app.get("/")
47
  def root():
48
+ return Response(status_code=status.HTTP_200_OK, data='ok')
49
 
50
  @app.get("/health")
51
  def healthcheck():
52
+ return Response(status_code=status.HTTP_200_OK, data='ok')
53
+
54
+ @app.post("/hi_mlhub")
55
+ async def hi_mlhub(payload: RequestPayload):
56
+ if manager.available is not None:
57
+ request_id, compressed_data = package.gzip(payload)
58
+
59
+ # Send binary data to all connected WebSocket clients
60
+ await manager.send_bytes(manager.available, compressed_data)
61
 
62
+ try:
63
+ # Wait for the response with a timeout (e.g., 10 seconds)
64
+ data = await asyncio.wait_for(manager.listen(manager.available, request_id), timeout=10.0)
65
+ return JSONResponse(status_code=status.HTTP_200_OK, content=data)
66
+ except Exception:
67
+ return JSONResponse(status_code=status.HTTP_504_GATEWAY_TIMEOUT, content={ "error": "Timeout" })
68
+ else:
69
+ return JSONResponse(status_code=status.HTTP_502_BAD_GATEWAY, content={ "error": "MLaaS is not available." })
70
+
71
+ # Simple token-based authentication dependency
72
+ def is_valid_token(token: str):
73
+ return token == WEBSOCKET_SECURE_TOKEN
74
+
75
+ def is_valid_apikey(channel_id: str):
76
+ return channel_id is not None and channel_id in WHITELIST_CHANNEL_IDS
77
+
78
  # WebSocket endpoint
79
  @app.websocket("/ws")
80
+ async def websocket_endpoint(websocket: WebSocket):
81
+ headers = websocket.headers
82
+ token = headers.get("x-token")
83
+ channel_id = headers.get("x-channel-id")
84
+
85
+ if not is_valid_token(token):
86
+ return HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
87
+ if not is_valid_apikey(channel_id):
88
+ return HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="No permission")
89
+
90
+ await manager.connect(channel_id, websocket)
91
+
92
  try:
93
  while True:
94
+ # Common receiver
95
+ data = await manager.receive_text(channel_id)
96
+ print(f"Message from MLaaS: {data}")
97
+
98
+ # Notify the manager that a message was received
99
+ await manager.notify(channel_id, data)
100
+
101
+ # Broadcast the message to all clients
102
+ #await manager.broadcast(f"Client {channel_id} says: {data}")
103
  except WebSocketDisconnect:
104
+ manager.disconnect(channel_id)
105
+ await manager.broadcast(f"A client has disconnected with ID: {channel_id}")
106
+
107
+ return None
108
 
109
  def is_valid(u, p):
110
  return u == X_REQUEST_USER and p == X_API_KEY
models/connection_manager.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import json
3
+ import logging
4
+ from fastapi import HTTPException, WebSocket, status
5
+ from typing import Dict
6
+
7
+ class InRequest:
8
+ def __init__(self):
9
+ self.responses: Dict[str, asyncio.Future] = {}
10
+
11
+ class ConnectionManager:
12
+
13
+ def __init__(self):
14
+ self.available = None
15
+ self.active_connections: Dict[str, WebSocket] = {} # Maps socket ID to WebSocket connection
16
+ self.in_request: Dict[str, InRequest] = {} # Store pending response futures
17
+
18
+ async def connect(self, socket_id: str, websocket: WebSocket):
19
+ await websocket.accept()
20
+ self.active_connections[socket_id] = websocket
21
+ if self.available is None:
22
+ self.available = socket_id
23
+ return socket_id
24
+
25
+ def disconnect(self, socket_id: str):
26
+ if socket_id in self.active_connections:
27
+ del self.active_connections[socket_id]
28
+ if self.available == socket_id:
29
+ self.available = None
30
+
31
+ async def broadcast(self, message: str):
32
+ for connection in self.active_connections.values():
33
+ await connection.send_text(message)
34
+
35
+ async def receive_text(self, socket_id: str):
36
+ websocket = self.active_connections.get(socket_id)
37
+ if websocket:
38
+ return await websocket.receive_text()
39
+ else:
40
+ raise HTTPException(
41
+ status_code=status.HTTP_502_BAD_GATEWAY,
42
+ detail=f"Socket ID {socket_id} not connected")
43
+
44
+ async def send_text(self, socket_id: str, message: str):
45
+ websocket = self.active_connections.get(socket_id)
46
+ if websocket:
47
+ await websocket.send_text(message)
48
+ else:
49
+ raise HTTPException(
50
+ status_code=status.HTTP_502_BAD_GATEWAY,
51
+ detail="WebSocket connection not found.")
52
+
53
+ async def send_bytes(self, socket_id: str, binary_data: bytes):
54
+ websocket = self.active_connections.get(socket_id)
55
+ if websocket:
56
+ await websocket.send_bytes(binary_data) # Send binary data
57
+ else:
58
+ raise HTTPException(
59
+ status_code=status.HTTP_502_BAD_GATEWAY,
60
+ detail=f"Socket ID {socket_id} not connected")
61
+
62
+ async def listen(self, socket_id:str, request_id:str) -> str:
63
+ req = InRequest()
64
+ # Create a Future for waiting for the response
65
+ future = asyncio.get_event_loop().create_future()
66
+ req.responses[request_id] = future
67
+ self.in_request[socket_id] = req
68
+ try:
69
+ return await future # Await the future until it's set with a response
70
+ except asyncio.CancelledError:
71
+ raise HTTPException(
72
+ status_code=status.HTTP_502_BAD_GATEWAY,
73
+ detail=f"Socket ID {socket_id} not connected or canceled")
74
+
75
+ async def notify(self, socket_id: str, message: str):
76
+ logging.debug(message)
77
+ # If there is a pending future for this socket, set the result
78
+ if socket_id in self.in_request:
79
+ request_id, payload = self.extract_message(message)
80
+ if request_id is not None:
81
+ self.in_request[socket_id].responses[request_id].set_result(payload)
82
+ self.in_request.pop(socket_id, None)
83
+
84
+ def extract_message(self, message:str):
85
+ request_id = None
86
+ payload = None
87
+ logging.debug(message)
88
+
89
+ try:
90
+ o = json.loads(message)
91
+ if o is not None:
92
+ request_id, payload = o.get('request_id'), o.get('payload')
93
+ except Exception as e:
94
+ logging.warning(f"extract_message error: {str(e)}")
95
+
96
+ return request_id, payload
models/gateway_payload.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+
3
+ class GwPayload(BaseModel):
4
+ request_id: str
5
+ payload: str
models/request_payload.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+
3
+ class RequestPayload(BaseModel):
4
+ request: object
requirements.txt CHANGED
@@ -1,4 +1,5 @@
1
  python-dotenv==1.0.1
2
  fastapi==0.115.2
3
  uvicorn==0.31.1
4
- websockets==13.1
 
 
1
  python-dotenv==1.0.1
2
  fastapi==0.115.2
3
  uvicorn==0.31.1
4
+ websockets==13.1
5
+ pydantic==2.9.2
utils/package_manager.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gzip
2
+ import json
3
+ import uuid
4
+
5
+ from models.request_payload import RequestPayload
6
+
7
+ class PackageManager:
8
+ def gzip(self, payload: RequestPayload):
9
+ request_id = str(uuid.uuid4())
10
+
11
+ json_object = {
12
+ "request_id": request_id,
13
+ "payload": payload.request # Use the incoming data
14
+ }
15
+
16
+ # Convert JSON object to binary then zip it
17
+ binary_data = json.dumps(json_object).encode('utf-8')
18
+ compressed_data = gzip.compress(binary_data)
19
+ return request_id, compressed_data