Spaces:
Paused
Paused
Download connection_manager.py from arpy8/contorller-socket: direct link, hf CLI and curl.
- Browser
- Download file 1.26 kB
-
https://huggingface.co/spaces/arpy8/contorller-socket/resolve/main/connection_manager.py
- Command line
-
hf download hf://spaces/arpy8/contorller-socket/connection_manager.py
-
curl -L -o connection_manager.py https://huggingface.co/spaces/arpy8/contorller-socket/resolve/main/connection_manager.py
1.26 kB
| import time | |
| from dataclasses import dataclass | |
| from typing import Dict, Optional | |
| import websockets | |
| class Session: | |
| token: str | |
| websocket: websockets.WebSocketServerProtocol | |
| last_activity: float | |
| def update_activity(self): | |
| self.last_activity = time.time() | |
| class ConnectionManager: | |
| def __init__(self, session_timeout: int = 3600): | |
| self.sessions: Dict[str, Session] = {} | |
| self.session_timeout = session_timeout | |
| def create_session(self, token: str, websocket: websockets.WebSocketServerProtocol) -> Optional[Session]: | |
| if token in self.sessions: | |
| return None | |
| session = Session(token=token, websocket=websocket, last_activity=time.time()) | |
| self.sessions[token] = session | |
| return session | |
| def remove_connection(self, token: str): | |
| self.sessions.pop(token, None) | |
| def cleanup_expired_sessions(self): | |
| current_time = time.time() | |
| expired_tokens = [ | |
| token for token, session in self.sessions.items() | |
| if current_time - session.last_activity > self.session_timeout | |
| ] | |
| for token in expired_tokens: | |
| self.remove_connection(token) | |