Factor Studios commited on
Commit
81577f4
·
verified ·
1 Parent(s): 42cb2ee

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +76 -3
server.py CHANGED
@@ -34,16 +34,89 @@ class VirtualGPUServer:
34
  # Active connections and sessions
35
  self.active_connections: Dict[str, WebSocket] = {}
36
  self.active_sessions: Dict[str, Dict[str, Any]] = {}
 
 
37
 
38
  # Performance monitoring
39
  self.ops_counter = 0
40
  self.start_time = time.time()
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  async def handle_vram_operation(self, operation: dict) -> dict:
43
  """Handle VRAM read/write operations"""
44
- op_type = operation.get('type')
45
- block_id = operation.get('block_id')
46
- data = operation.get('data')
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  if op_type == 'write':
49
  # Generate unique file path for this block
 
34
  # Active connections and sessions
35
  self.active_connections: Dict[str, WebSocket] = {}
36
  self.active_sessions: Dict[str, Dict[str, Any]] = {}
37
+ self.heartbeat_interval = 5 # seconds
38
+ self.connection_timeout = 30 # seconds
39
 
40
  # Performance monitoring
41
  self.ops_counter = 0
42
  self.start_time = time.time()
43
 
44
+ def _make_json_serializable(self, obj):
45
+ """Convert non-JSON-serializable objects to serializable format"""
46
+ if isinstance(obj, dict):
47
+ return {k: self._make_json_serializable(v) for k, v in obj.items()}
48
+ elif isinstance(obj, list):
49
+ return [self._make_json_serializable(i) for i in obj]
50
+ elif isinstance(obj, tuple):
51
+ return list(obj)
52
+ elif isinstance(obj, (np.ndarray, np.generic)):
53
+ return obj.tolist()
54
+ elif isinstance(obj, (Path, uuid.UUID)):
55
+ return str(obj)
56
+ elif hasattr(obj, '__dict__'):
57
+ # Handle custom objects by converting their __dict__ to serializable format
58
+ return self._make_json_serializable(obj.__dict__)
59
+ elif isinstance(obj, (int, float, str, bool, type(None))):
60
+ return obj
61
+ else:
62
+ # Convert any other types to string representation
63
+ return str(obj)
64
+
65
+ async def monitor_connection(self, websocket: WebSocket, session_id: str):
66
+ """Monitor connection health and handle reconnection"""
67
+ try:
68
+ while session_id in self.active_connections:
69
+ try:
70
+ await asyncio.wait_for(websocket.receive_text(), timeout=self.heartbeat_interval)
71
+ except asyncio.TimeoutError:
72
+ try:
73
+ await websocket.send_json({"type": "ping"})
74
+ except:
75
+ print(f"Connection lost for session {session_id}")
76
+ break
77
+ except Exception:
78
+ break
79
+ await asyncio.sleep(self.heartbeat_interval)
80
+ finally:
81
+ await self.handle_disconnect(session_id)
82
+
83
+ async def handle_disconnect(self, session_id: str):
84
+ """Clean up resources when a client disconnects"""
85
+ if session_id in self.active_connections:
86
+ try:
87
+ await self.active_connections[session_id].close()
88
+ except:
89
+ pass
90
+ del self.active_connections[session_id]
91
+ if session_id in self.active_sessions:
92
+ # Save any pending state before removing session
93
+ session_data = self.active_sessions[session_id]
94
+ if session_data.get('pending_state'):
95
+ await self.handle_state_operation({
96
+ 'type': 'save',
97
+ 'component': 'session',
98
+ 'state_id': session_id,
99
+ 'data': session_data['pending_state']
100
+ })
101
+ del self.active_sessions[session_id]
102
+
103
  async def handle_vram_operation(self, operation: dict) -> dict:
104
  """Handle VRAM read/write operations"""
105
+ try:
106
+ op_type = operation.get('type')
107
+ block_id = operation.get('block_id')
108
+ data = operation.get('data')
109
+
110
+ # Handle non-serializable objects
111
+ if data and isinstance(data, (dict, list)):
112
+ data = self._make_json_serializable(data)
113
+
114
+ if op_type == 'write':
115
+ # Additional error handling and logging
116
+ if not block_id:
117
+ raise ValueError("Missing block_id for VRAM write operation")
118
+ if data is None:
119
+ raise ValueError("Missing data for VRAM write operation")
120
 
121
  if op_type == 'write':
122
  # Generate unique file path for this block