File size: 1,257 Bytes
e500fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import time
from dataclasses import dataclass
from typing import Dict, Optional
import websockets

@dataclass
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)